DropDownList Helper Data Binding in MVC

In this post you will learn how to bind data to a DropDownList helper in MVC. We will try binding data to a DropDownList from a List<SelectListItem>, a List<Model> and also from a database.

I’ve created three DDL helper on the view page and to bind each DDL we will use different approach.


Let’s bind each DDL using different approaches:

1st Approach

In this approach, I am going to bind a Country DDL with List<SelectListItem> data, here is the code I’m using in the action method.


Notice two things in above code:

First: I have created a List<SelectListItem> that is IEnumerable<SelectListItem> and adding 3 items to country object. The IEnumerable<SelectListItem> created above is added to the ViewBag with the name Country. This is how we pass the IEnumerable<SelectListItem> implicitly to the DDL helper shown below.

@Html.DropDownList("Country", String.Empty)

In the above code, the helper accepts two parameters. The first parameter named DDL ("Country") is compulsory parameter and it should be similar to ViewBag (ViewBag.Country) name and the second, optionLabel, is not compulsory. The optionLabel is generally used the for first option in DDL. For example, if I use

@Html.DropDownList("Country", "Select Country")

If you would like to add any attribute like class attribute, that's the way

@Html.DropDownList("Country", null, "Select Country", new { @class = "form-control" })
 
Then, it will render following output.


Second: We can pass the IEnumerable<SelectListItem> explicitly to the DropDownList helper or we can add the IEnumerable<SelectListItem> to the ViewBag using the same name for the SelectListItem as the model property, look at the code how four different overloads arranged.



2nd Approach

In this approach, I am going to bind Language DDL with List<Gender> data, here Gender is a predefined model; here is the code I’m using in action method.


In above code, rather adding data in country.Add(new SelectListItem { Text = "", Value = "", Selected = "" }), I’m adding to Gender properties which is Id and Name.

3rd Approach

In this approach, I am going to bind Gender DDL with database data.


Again, database has two field Id and Name. Field Name is being used for data value field and data text field. “Male” will be the pre-selected value in DDL.

Complete Action Method Code

Now let me put all above approach in the same action method.


Complete View Page Code

I created a quick form and placed all three DDL helpers inside, when user will click the submit button form data will be passed to POST version of DDLBinding action method which will be in Home controller. By default, Html.BeginForm overload takes no parameters. The no parameter version defaults to posting the form data to the POST version of the same action method and controller.


Now, when user will click on submit button HTTP POST will execute and selected items will be passed to DDLBinding action method which has POST version with query string.



Here is the POST version of DDLBinding action method.


Hope this helps.

Comments

  1. Makes sense, is the purpose of having to action methods on the controller because their might be another way that the fields would arrive (perhaps in a bound model) and you want to point all the post methods to a single "view" method?

    Thanks!

    ReplyDelete
    Replies
    1. Accepting the Fields inside a dedicated Model class should be the right approach.
      Also you can define the options in a model class and fill it insde a viewfactory class.

      public class ViewModel{
      List Items {get; set;}
      public string Item{get; set;}
      }

      In get method fill the Items list with options, and accept viewmodel as paramter for Post method.

      use Item property to fill your DB.

      This will keep your code clean.

      Delete
  2. Looks good!! Could you also tell how to do the same thing with use of JQuery?

    ReplyDelete
    Replies
    1. Hari: I am going to write a blog post on jQuery Ajax calls by tomorrow, be tuned.

      Delete
    2. post is ready here http://www.itorian.com/2013/02/jquery-ajax-get-and-post-calls-to.html

      Delete
  3. Thanks, loads . . . I like the clean straightforward outlay of this example. Some of the new features of ASP.Net 4 that you have demonstrated in the 'HTTP POST' routine especially with the "THANKS" subroutine call!!

    Thanks . . .!!
    TomJ

    BTW: On another subject . . . Is there a easy way to change the format of the output fields from a VERTICAL position to a HORIZONTAL position? I've been looking for examples of this and have been unable to locate any useful examples of how to approach this. :-()

    ReplyDelete
  4. While this code works, I feel that it tends to cause too many problems when people modify it. For example, if the user changes the code to pass the SelectList as an object in the ViewModel and calls it Country, MVC now generates a vague and difficult error about there being parameterless constructor. (Stack Overflow is filled with questions explicitly with this problem). I feel it's much better to provide examples that use dedicated view models, use separate selection id properties, and use DropDownListFor rather than DropDownList. It's also best not to rely on the obscure behavior of the model binder with dropdownlists.

    ReplyDelete
  5. Hi,

    I am trying your second approach and i am getting this exception
    There is no ViewData item of type 'IEnumerable' that has the key 'Source'.

    ReplyDelete

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System