DropDownListFor Not Selecting Value

If you're doing it properly and using a model--unlike all these ViewBag weirdos--and still seeing the issue, it's because @Html.DropDownListFor(m => m.MyValue, @Model.MyOptions) can't match MyValue with the choices it has in MyOptions. The two potential reasons for that are:

  1. MyValue is null. You haven't set it in your ViewModel. Making one of MyOptions have a Selected=true won't solve this.
  2. More subtly, the type of MyValue is different than the types in MyOptions. So like, if MyValue is (int) 1, but your MyOptions are a list of padded strings {"01", "02", "03", ...}, it's obviously not going to select anything.

After researching for an hour, I found the problem that is causing the selected to not get set to DropDownListFor. The reason is you are using ViewBag's name the same as the model's property.

Example

public  class employee_insignia
{ 
   public int id{get;set;}
   public string name{get;set;}
   public int insignia{get;set;}//This property will store insignia id
}

// If your ViewBag's name same as your property name 
  ViewBag.Insignia = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);

View

 @Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.Insignia, "Please select value")

The selected option will not set to dropdownlist, BUT When you change ViewBag's name to different name the selected option will show correct.

Example

ViewBag.InsigniaList = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);

View

 @Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.InsigniaList , "Please select value")

Tags:

Asp.Net Mvc