So, without much ado, here is the code -
Your ViewModel (or Model depending on the architecture/approach) and helper classes look like the below -
//This class contains the keys, values and whatever other model related data that needs to be bound to the dropdown
public class DropDownItem { public int DropDownKey { get; set; } public string DropDownValue { get; set; }
//This class is an overly simplified ViewModel
public class DropDownTestViewModel { public DropDownSelectedValue { get; set; } //This represents the actual selected value public IListDropDownItemCollection = new List (); //This represents the list of all options in the dropdown }
//This is the simplified View code -
@Html.DropDownListFor(imf => Model.DropDownSelectedValue, new SelectList(Model.DropDownItemCollection.AsEnumerable(), "DropDownKey", "DropDownValye", Model.DropDownSelectedValue), " -- Please Select --", new { id = "ddl" + rowCount })
The code looks pretty straightforward but the way MVC4 is designed, it'll never work. The dropdownlist will neither show the selected value nor post it back. And it will not tell you what is wrong either!! :)
So, what is wrong here? After many iterations of writing and rewriting different variations of the code, I found that the problem is that the model items **MUST** be properties. So, to fix the above, we just need to add getters and setters as follows -
public IListDropDownItemCollection = new List ();
becomes this -
public IListDropDownItemCollection { get; set; } //Initialize in constructor etc as needed
And hooray, the dropdown shows and posts back correct selected values and the world makes sense again. :)
No comments:
Post a Comment