Model Binding with Dropdown List in ASP.NET 4.5
By | December 20, 2011

ASP.NET Forms 4.5 Preview introduces new model binding for  ASP.NET web forms. The concept of model binding was first introduced with ASP.NET MVC and now it has incorporated with ASP.NET Web Forms. You can easily perform any CURD operation with any sort of data controls using any data access technology like Entity Framework,  ADO.NET, LINQ to SQL Etc.  In this post I am going talk about how you can bind the data with ASP.NET DropdownList using new Model Binding features.

Let’s say we have a speaker database and we wants to bind the name of the speakers with the DropDownList.  First placed an ASP.NET Dropdown control with the page  and set the “DataTextField” and “DataValueField” properties.

image thumb11 Model Binding with Dropdown List in ASP.NET 4.5

We can set the  ddlName.DataSource to specifying the data source from the code behind and bind the data with dropdpwnlist, but  in this case from the code behind to providing the data source.

Now, instead of specifying the DataSource, we will be setting the Dropdownlists SelectMethod property to point a method GetSpeakerNames() within the code-behind file.

image thumb12 Model Binding with Dropdown List in ASP.NET 4.5

Select method is expected to return us result of type IQueryable<TYPE>. Here is GetSpeakerName() method is defined as follows.

/// <summary>
/// Return the Speakers Name
/// </summary>
/// <returns></returns>
public IQueryable<Speaker> GetSpeakerNames()
DeveloperConferenceDBEntities datasource = new DeveloperConferenceDBEntities();
return datasource.Speakers;

So, Instead of specifying the data source we are specifying the SelectMethod, which return the IQueryable type of Speaker object. Run the application, you will find the names binded with dropdown list.

image thumb13 Model Binding with Dropdown List in ASP.NET 4.5

Hope this helps !

Cheers !