Monday, April 21, 2014

Working with the DropDownList control in ASP.NET MVC

If you are using Model Binding with ASP.NET MVC, one of the most confusing control elements is the use of the DropDownList control.
Unlike the TextBox controls and other simplistic input controls, the DropDownList control requires a collection of items.  Even more so, it requires a Name/Value pair collection of items in order to populate the collection.  On top of that, in the [HttpPost] method in your Controller, you need to be able to get the selected value from the DropDownList control and use it for any additional operations you need to perform.
Well, to get started, in order to set up Model Binding for a DropDownList control, you will need to set up a property in your Model similar to this:
public IList<SelectListItem> Countries {get; set;}

However, since you cannot use that property to send back the value to your [HttpPost] method, you will need to set up an additional property to hold the value returned when the Page is posted such as this:

public string SelectedCountry {get; set;}

Finally, you will need to set up the binding in your ASP.NET MVC View:

@Html.DropDownListFor(model=>model.SelectedCountry, Model.Countries, "--Select—")

Now, when you need to access the value from the DropDownList, you can simply use the model.SelectedCountry property value!

NOTE: One of the quirks in using the DropDownList control in ASP.NET MVC is that if your View fails ModelState validation, since there is no ViewState (unlike ASP.NET Web Forms), the contents of the DropDownList will not be available in the [HttpPost] method if you bound the results in the [HttpGet] method (for example, by loading the values from a database or an XML file by using a LINQ query).  Therefore, you will have to RE-BIND any populated content values in the [HttpPost] method as well in order to avoid any exception messages (especially if you are simply returning the same View bound to the model i.e.

If you think that Microsoft should improve the handling of DropDownLists in ASP.NET MVC to make it easier to persist as part of model data, then you should vote for this UserVoice item here:

No comments:

Post a Comment