Saturday, June 20, 2015

MVC4 - How to Bind Dropdowns lists and retain selected values during postbacks

I recently had a lot of trouble with dropdowns in MVC4. Either the dropdowns don't get populated, or they don't show the selected value, or they just don't postback the selected values. It's pretty straightforward to do these things in weakly typed Views but I wanted to make it all work with strongly typed Views because it results in a cleaner code in the long run.

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 IList DropDownItemCollection  = 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 IList DropDownItemCollection  = new List();


becomes this -
public IList DropDownItemCollection   { 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