pages

Thursday, 10 October 2013

Working with DropDownLists in Asp.net MVC


Drop down list in mvc is quiet different from drop down list control in web forms.

The reason being the Drop down list control in web form is so brilliant that whatever collection we give to it, it will take it quietly and do all the hard work from its side.

But in Asp.net MVC scenario is little different. Here Drop Down List Helper takes only List<SelectListItem>.

So This is a class added for storing drop down list values. It is under System.Web.Mvc namespace
It has 3 Properties: Name, Value, Selected.
Selected is bool and rest two are string type.

There are 2 types of data you can fill Dropdown list with:
1) InMemory collection.
2) From Database.

For InMemory Collection you have to create a list of 
List<SelectListItem>
either in View or in controller( later pass it to view).
This is how you can create it in controller.

Same can be done in View also. But Then passing data to view from Controller will not be true in that case as you are preparing the data in view itself.

From Database
While selecting the data from database you can directly convert the data to List of SelectListItem.

If you want you view to Generate Dropdownlist for you the you have create a propery with List<SelectListItem> in your Model.
public List<SelectListItem> MyDropDownList { get; set; }

But while submitting the page it will not give you SelectList Item. Instead Drop down list will return a simple string value just like Textbox.

I hope this is enough for start working with Drop down list.
For any queries comment below.