C# MVC 3 Using Selectlist with Selected Value in View

C# mvc 3 using selectlist with selected value in view

@Html.DropDownListFor(model=>model.Categories, Model.Categories, Model.CategoryId)

Here you are not properly using the helper method. The first argument must be a property on your view model which will contain the currently selected value. It should be a scalar property, not a collection.

So in your view model you need to add such property:

[Display(Name = "Categorie")]
public IEnumerable<SelectListItem> Categories { get; set; }
public string SelectedValue { get; set; }

And in your controller action:

var selectList = listOfCategories.Select(x => new SelectListItem {
Text = x.Name,
Value = x.Id.ToString()
}).ToList();

var viewModel = new BlogModel
{
BlogId = blogToEdit.Id,
Active = blogToEdit.Actief,
Content = blogToEdit.Text,
Title = blogToEdit.Titel,
Categories = selectList,
// this is what sets the selected value
SelectedValue = blogToEdit.Category.Id
};

And in your view simply:

@Html.DropDownListFor(x => x.SelectedValue, Model.Categories)

Selected item in SelectList not being displayed in view drop-down

This one has bitten me a few times in the past, all the way back to MVC 3 or so.

Basically, if you're passing a model to your view (i.e. using a @model MyTypeOfViewModel directive) and binding a select to a property on that model, then the selected value of the select list is the value of the property you are binding to on your view model. Setting the selected item in a select list directly will be ignored.

In your case, it's SeasonID from this:

<select asp-for="SeasonID" ...>

So for you to select Season 2, you'd need to set the value of the SeasonID property on your view model to the ID of Season 2:

var viewModel = new SeasonViewModel
{
SeasonID = // Season 2's SeasonID
}

However, if you're not binding the value of the select directly, creating the select like this:

// Notice I've not specified `asp-for`.
<select class="form-control" asp-items="ViewBag.Seasons"></select>

will use the selected value you set when creating the SelectList. That said, your code to do that is currently slightly wrong. It should be:

var selected = _context.Seasons
.Where(s => s.IsCurrent == true)
.FirstOrDefault();
ViewData["Seasons"] = new SelectList(
_context.Seasons,
"ID",
"SeasonName",
// It needs to be the actual value of the field, not the season's object.
selected?.ID.ToString());

In short, if you want to bind to your SeasonID property, create your SelectList, without selecting a value, like so:

ViewData["Seasons"] = new SelectList(
_context.Seasons,
"ID",
"SeasonName");

Then set the selected value on the view model itself, and the asp-for attribute on the select will do the rest.

How to show selected value in a DropDownList Html Helper using ViewBag in C#

ViewBag is not working in your case, you will have to select an option manually, using Selected=true. HtmlDropDown is an outdated helper too.

Using html5 select with an asp helper is the best way to select item automatically

view

@{

var currentType = "2";
List<SelectListItem> contentData = new List<SelectListItem>();
contentData.Add(new SelectListItem
{
Text = "Show 0 only",
Value = "0",
});

contentData.Add(new SelectListItem
{
Text = "Show 2 Only",
Value = "2",
});

//or I guess you can take the from viewbag

string currentType = ViewBag.currentType;
List<SelectListItem> contentData = ViewBag.currentData
}

.....

<select class="form-control" id="levels" asp-for="@currentType"
asp-items="@contentData">
<option value="0" > Select </option>
</select>

this is working for dropdown list

@{
currentType = ViewBag.currentType;
contentData = ViewBag.contentData;

var dropDownItems = new SelectList(contentData,"Value","Text", currentType);
}
.....

@Html.DropDownList("@currentType",@dropDownItems,"Select",new { @class = "form-control" })

How to get DropDownList Selected Value in MVC

Your view model should be the class which represents the properties needed by your view. So if you want to add a dropdown to your view, add 2 more properties to your viewmodel, one for the list of items needed to build the select options and another for the selected option value.

public class ResourceViewModel
{
public int DeveloperTypeId { set;get;}
public List<SelectListItem> DeveloperTypes { set;get;}

public string FirstName {get; set;}
public string LastName {get; set;}
}

Now in your GET action, create an object of this view model, initialize the DeveloperTypes collection property and send the object to the view.

public ActionResult NewUser()
{
var vm = new ResourceViewModel();
vm.DeveloperTypes = db_RIRO.sp_GetAllDeveloperType()
.Select(a=> new SelectListItem {
Value = a.DeveloperTypeID.ToString(),
Text= a.Developer_Type })
.ToList();
return View(vm);
}
[HttpPost]
public void AddUser(ResourceViewModel model)
{
//check model.DeveloperTypeId
// to do : Return something
}

Assuming db_RIRO.sp_GetAllDeveloperType() returns a collection of objects with a DeveloperTypeID property of int type and a Developer_Type of string type.

Now in your view, you can use DropDownListFor helper

@model ResourceViewModel
@using(Html.BeginForm("AddUser","Resource"))
{
@Html.LabelFor(a=>a.FirstName)
@Html.TextBoxFor(a=>a.FirstName)

@Html.LabelFor(a=>a.LastName)
@Html.TextBoxFor(a=>a.LastName)

@Html.LabelFor(a=>a.DeveloperTypeId)
@Html.DropDownListFor(a=>a.DeveloperTypeId, Model.DeveloperTypes,"Select");

<button type="submit" class="btn">Submit</button>
}

Set the selected item in dropdownlist in MVC3

First, create your ViewModel.

public class MovieViewModel
{
public string Genre { get; set; }

public IEnumerable<SelectListItem> GenreList
{
get
{
yield return new SelectListItem { Text = "Comedy", Value = "1" };
yield return new SelectListItem { Text = "Drama", Value = "2" };
yield return new SelectListItem { Text = "Documentary", Value = "3" };
}
}
}

Then, your controller creates a new instance of this ViewModel and sends it to the view.

public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
var viewModel = new MovieViewModel
{
Genre = "2"
};

return View(viewModel);
}
}

Finally, the view displays the dropdownlist using the ASP.NET wrapper [Html.DropDownListFor()][1].

@model MvcApplication1.Models.MovieViewModel

<!DOCTYPE html>

<html>
<head>
<title>My movie</title>
</head>
<body>
<div>
@Html.DropDownListFor(m => m.Genre, Model.GenreList)
</div>
</body>
</html>

The selected value is then automatically chosen according the ViewModel. There's no need to manually set the Selected property of the objects SelectListitem.

How to get DropDownList SelectedValue in Controller in MVC

1st Approach (via Request or FormCollection):

You can read it from Request using Request.Form , your dropdown name is ddlVendor so pass ddlVendor key in the formCollection to get its value that is posted by form:

string strDDLValue = Request.Form["ddlVendor"].ToString();

or Use FormCollection:

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{
string strDDLValue = form["ddlVendor"].ToString();

return View(MV);
}

2nd Approach (Via Model):

If you want with Model binding then add a property in Model:

public class MobileViewModel 
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectedVendor {get;set;}
}

and in View:

@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")

and in Action:

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{
string SelectedValue = MV.SelectedVendor;
return View(MV);
}

UPDATE:

If you want to post the text of selected item as well, you have to add a hidden field and on drop down selection change set selected item text in the hidden field:

public class MobileViewModel 
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectVendor {get;set;}
public string SelectedvendorText { get; set; }
}

use jquery to set hidden field:

<script type="text/javascript">
$(function(){
$("#SelectedVendor").on("change", function {
$("#SelectedvendorText").val($(this).text());
});
});
</script>

@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
@Html.HiddenFor(m=>m.SelectedvendorText)

MVC - Set selected value of SelectList

If you have your SelectList object, just iterate through the items in it and set the "Selected" property of the item you wish.

foreach (var item in selectList.Items)
{
if (item.Value == selectedValue)
{
item.Selected = true;
break;
}
}

Or with Linq:

var selected = list.Where(x => x.Value == "selectedValue").First();
selected.Selected = true;

How to properly send SelectedValue of DropDownList from View to controller? ViewModel

As per the comment,

I want DropDownListFor where I can choose just one DateTime value
which I can send to ActionResult List()

Since you want to select only one item, you do not need an array. Also change your type (of the property which gets the selected item) to a valid type so that Model binding will be able to map the date (string) value to the property of your view model.

public class ScheduleViewModel
{
public DateTime? SelectedDate { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
public Schedule OneSchedule { get; set; }
}

Now in your view,

@model ScheduleViewModel
@using(Html.BeginForm())
{
@Html.DropDownListFor(x => x.SelectedDate, Model.Values)
<input type="submit" />
}

And in your HttpPost action,

[HttpPost]
public ActionResult List(ScheduleViewModel model)
{
if(model.SelectedDate!=null)
{
//Safe to access model.SelectedDate.Value now :)
}
// to do : Return something
}


Related Topics



Leave a reply



Submit