Html.DropdownList No value set for selected value

How can I set the selected value to Html.DropDownListFor? I look online and see that it can be achieved using the fourth parameter, as shown below:

@Html.DropDownListFor(m => m, new SelectList(Model, "Code", "Name", 0), "Please select a country") 

My picklist is then displayed as follows:

 <select id="ShipFromCountries" name="ShipFromCountries"> <option value="">Please select a country</option> <option value="GB">United Kingdom</option> <option value="US">United States</option> ... </select> 

But for some reason, the United Kingdom remains selected, but I want the “select country” to be selected.

Does anyone know how I can achieve this?

EDIT

I updated my code as there was a slight change in functionality, however it still looks like this problem. This is what in my opinion:

 @Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template") 

1 is the option identifier I want to select, I also tried with the option text, but this also does not work.

Any ideas?

+87
asp.net-mvc razor
Oct 20 '13 at 10:54 on
source share
12 answers

There are some conceptual problems in the code:

First

 @Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template") 

When using DropDownListFor, the first parameter is the property in which your selected value is saved after the form is submitted. So, in your case, you must have SelectedOrderId as part of your model or something like that in order to use it like this:

 @Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template") 

Second

Apart from using the ViewBag, this is not the case, but there are more efficient ways (instead of putting this information in the ViewModel), there is a small error (or unexpected behavior) when the ViewBag property where you hold the SelectList has the same property name in which you put the selected value. To avoid this, simply use a different name, naming the property containing the list of elements.

Some code that I would use if I were you to avoid these problems and write better MVC code:

ViewModel:

 public class MyViewModel{ public int SelectedOrderId {get; set;} public SelectList OrderTemplates {get; set;} // Other properties you need in your view } 

Controller:

 public ActionResult MyAction(){ var model = new MyViewModel(); model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1); //Other initialization code return View(model); } 

In your view

 @Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template") 
+161
Nov 15 '13 at 19:14
source share

I didn’t succeed, it worked like this:

controller:

 int selectedId = 1; ViewBag.ItemsSelect = new SelectList(db.Items, "ItemId", "ItemName",selectedId); 

Look:

 @Html.DropDownListFor(m => m.ItemId,(SelectList)ViewBag.ItemsSelect) 

JQuery:

 $("document").ready(function () { $('#ItemId').val('@Model.ItemId'); }); 
+19
Dec 12 '14 at 5:19
source share

When you pass an object like this:

 new SelectList(Model, "Code", "Name", 0) 

You say: Source ( Model ) and Key ( "Code" ) Text ( "Name" ) and the selected value is 0 . Your source may not have a value of 0 for the Code property, so the HTML helper will select the first element to pass the actual selectedValue to this control.

+6
Oct. 20 '13 at 12:48 on
source share

Before assigning, be sure to trim the selected value.

// Model

 public class SelectType { public string Text { get; set; } public string Value { get; set; } } 

//controller

 var types = new List<SelectType>(); types.Add(new SelectType() { Value = 0, Text = "Select a Type" }); types.Add(new SelectType() { Value = 1, Text = "Family Trust" }); types.Add(new SelectType() { Value = 2, Text = "Unit Trust"}); ViewBag.PartialTypes = types; 

// view

 @Html.DropDownListFor(m => m.PartialType, new SelectList(ViewBag.PartialTypes, "Value", "Text"), new { id = "Type" }) 
+3
Nov 15 '13 at 18:43
source share

If you know what will be in the view, you can also set the default value from Controller, and then configure it in the view / cshtml file. No need to set a default value from the HTML side.

In the Controller file.

 commission.TypeofCommission = 1; return View(commission); 

In the .cshtml file.

 @Html.DropDownListFor(row => row.TypeofCommission, new SelectList(Model.commissionTypeModelList, "type", "typeName"), "--Select--") 
+2
Oct. 15 '15 at 6:31
source share

You have to forget the class

Selectlist

Use this in your controller:

 var customerTypes = new[] { new SelectListItem(){Value = "all", Text= "All"}, new SelectListItem(){Value = "business", Text= "Business"}, new SelectListItem(){Value = "private", Text= "Private"}, }; 

Select a value:

 var selectedCustomerType = customerTypes.FirstOrDefault(d => d.Value == "private"); if (selectedCustomerType != null) selectedCustomerType.Selected = true; 

Add list to ViewData:

 ViewBag.CustomerTypes = customerTypes; 

Use this in your View:

 @Html.DropDownList("SectionType", (SelectListItem[])ViewBag.CustomerTypes) 

-

Additional information: http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

0
Nov 27 '14 at 16:23
source share

Add Controller Section

  ViewBag.Orders= new SelectList(db.Orders, "Id", "business", paramid); 

Add Html Section

  @Html.DropDownList("Orders", null) 

Simple method

0
Jun 22 '15 at 12:54
source share

For me, a common solution :)

 @{ var selectedCity = Model.Cities.Where(k => k.Id == Model.Addres.CityId).FirstOrDefault(); if (selectedCity != null) { @Html.DropDownListFor(model => model.Addres.CityId, new SelectList(Model.Cities, "Id", "Name", selectedCity.Id), new { @class = "form-control" }) } else { @Html.DropDownListFor(model => model.Cities, new SelectList(Model.Cities, "Id", "Name", "1"), new { @class = "form-control" }) } } 
0
Jul 15 '15 at 8:26
source share

Linq for Dropdown with empty item selected item (works 100%)
(Strongly typed, probability of minimal error) Any changes to the model will be reflected in the binding

controller

 public ActionResult ManageSurveyGroup() { tbl_Survey sur = new tbl_Survey(); sur.Survey_Est = "3"; return View(sur); } 

View

  @{ //Step One : Getting all the list var CompEstdList = (from ComType in db.tbl_CompEstdt orderby ComType.Comp_EstdYr select ComType).ToList(); //Step Two : Adding a no Value item ** CompEstdList.Insert(0, new eDurar.Models.tbl_CompEstdt { Comp_Estdid = 0, Comp_EstdYr = "--Select Company Type--" }); //Step Three : Setting selected Value if value is present var selListEstd= CompEstdList.Select(s => new SelectListItem { Text = s.Comp_EstdYr, Value = s.Comp_Estdid.ToString() }); } @Html.DropDownListFor(model => model.Survey_Est, selListEstd) @Html.ValidationMessageFor(model => model.Survey_Est) 

This method for data binding is also possible.

 var selList = CompTypeList.Select(s => new SelectListItem { Text = s.CompTyp_Name, Value = s.CompTyp_Id.ToString(), Selected = s.CompTyp_Id == 3 ? true : false }); 
0
May 10 '16 at 9:12
source share

I know this is not the answer to the question, but I was looking for a way to initialize DropDownList from the list on the fly in the view as I continued to stumble about this post.

My mistake was that I tried to create a SelectList from the dictionary as follows:

 //wrong! @Html.DropDownListFor(m => m.Locality, new SelectList(new Dictionary<string, string>() { { Model.Locality, Model.Locality_text } }, Model.Locality, ... 

Then I started digging into the official msdn doc and found that DropDownListFor does not necessarily require a SelectList , but rather an IEnumerable<SelectListItem> :

 //right @Html.DropDownListFor(m => m.Locality, new List<SelectListItem>() { new SelectListItem() { Value = Model.Locality, Text = Model.Locality_text, Selected = true } }, Model.Locality, new { @class = "form-control select2ddl" }) 

In my case, I can probably also omit Model.Locality as the selected element, since its a) is the only element and b) it already talks about this in the SelectListItem.Selected property.

Just in case you are interested, the data source is an AJAX page that is dynamically loaded using the SelectWoo / Select2 control.

0
Jan 15 '18 at 11:57
source share
 public byte UserType public string SelectUserType 

You need to get one and install another. The selected value cannot be the same element that you are about to set.

 @Html.DropDownListFor(p => p.SelectUserType, new SelectList(~~UserTypeNames, "Key", "Value",UserType)) 

I use the Enum dictionary for my list, so there is a pair of "key", "value".

0
Jan 16 '18 at 12:59
source share

I had a similar problem, I used the same ViewBag and Element names. (Typo)

0
Oct 21 '18 at 21:51
source share



All Articles