Working with DropDownList in ASP.NET MVC

Sheonarayan
Posted by in ASP.NET MVC category on for Intermediate level | Points: 250 | Views : 95060 red flag
Rating: 4.6 out of 5  
 5 vote(s)

In this article, we are going to learn several tips and tricks of working with DropDownList in ASP.NET MVC.

Introduction

There are many scenarios while creating a data entry form in the web application, where we need to present the data in DropDownList or ListBox from which user can select one or multiple items. Binding those data from database or custom collection in ASP.NET MVC seems not very straight forward. In this article, we are going to learn some frequently faced problems and how to solve them.

How to bind static DropDownList items in ASP.NET MVC?


To bind static items in the DropDownList, we can pass collection of SelectListItem as data source of the DropDownList.
    @Html.DropDownList("dropRoles", new List<SelectListItem>()
    {
        new SelectListItem() { Text= "Yes", Value = "true" },
        new SelectListItem() { Text= "No", Value = "false", Selected = true }
    }, "Select ...")
In the above code snippet, first parameter is the name of the DropDownList, second parameter is the collection of SelectListItem to be used as the data source of the DropDownList and third parameter is the default value that will be selected if "Select = true" is not specified in any of the SelectListItem.

The above code will select No item from the DropDownList.


How to bind DropDownList from more than one tables data using Entitry Framework?


To bind the DropDownList from more than one database tables in Entity Framework, use below approach.

View code
@Html.DropDownList("MultipleTables", ViewBag.Roles as SelectList)
Controller action method code
 var data = from p in db.PersonalDetails
                       join f in db.Files
                       on p.AutoId equals f.PersonalDetailsId
                       select new 
                       {
                           PersonName = p.FirstName,
                           MyFileName = f.FileName
                       };

            SelectList list = new SelectList(data, "MyFileName", "PersonName");
            ViewBag.Roles = list;
In the above code snippet, we have joined two tables using LINQ and formed an object having PersonName and MyFileName property. The same is being converted into SelectList by specifying dataTextFileld and dataValueField of the DropDownList.

The SelectList collection is then being set as ViewBag.Roles and the same is being used as data source of the DropDownList in the View page.

How to write Select ... text as first item in DropDownList in ASP.NET MVC?


To write default empty item as "Select ..." in the DropDownList, pass the third parameter as "Select ...".
@Html.DropDownList("MultipleTables", ViewBag.Roles as SelectList, "Select ...")

How to write style / class or other HTML attributes to the DropDownList in ASP.NET MVC?


To write style/class or other HTML attributes to the DropDownList, pass 4th parameter as htmlObjectAttributes.

@Html.DropDownList("MultipleTables", ViewBag.Roles as SelectList, "Select ...", 
new { @class = "myClass", style = "width: 250px;" })

Output
<select class="myClass" id="MultipleTables" name="MultipleTables" style="width: 250px;"><option value="">Select ...</option>
<option value="Sheo File Name">Sheo</option>
<option value="Soumen File name">Soumen</option>
</select>

How to create a Model property that can be bounded to the DropDownList in ASP.NET MVC?


To create a Model property that can be bounded to the DropDownList, use below code snippet.
public IEnumerable<SelectListItem> Categories { get; set; }
Here we are creating Categories property that is of IEnumerable<SelectListItem> type.

Now in the Action method of the controller, set this property value like this
model.Categories = db.CategoryModels.Where(c => c.SectionId == sectionId &&
 c.Active == true).OrderBy(ct => ct.CategoryName).ToList().
Select(x => new SelectListItem { Value = x.CategoryId.ToString(), Text = x.CategoryName }).ToList();
In the above code snippet, notice the third line of the code in which we are selecting all the items from the List and creating SelectListItem object by specifying Value as CategoryId and Text as CategoryName.

When this collection is bounded to the DropDownList, CategoryId is used as value of the item and CategoryName is used as Text of the DropDownList item.

How to auto post back the form on change of DropDownList item in ASP.NET MVC?


To auto post back the form on change of DropDownList item in ASP.NET MVC, we can specify onchange attribute in htmlObjectAttributes like this.
@Html.DropDownList("MultipleTables", ViewBag.Roles as SelectList, "Select ...", 
new { @class = "myClass", style = "width: 250px;", onchange = "this.form.submit();" })
In the above code snippet, onchange attribute would force the form to submit it on the server when user is changing the selection in the DropDownList.

Conclusion

SelectList is basically the data source of the DropDownList in ASP.NET MVC and individual item of the DropDownList can be denoted by SelectListItem. By using these both objects we can manipulate the DropDownList in ASP.NET MVC.

Hope this article was useful. If you find any other problem related with DropDownList in ASP.NET MVC, let me know and I would try to solve and add in this article.

Thanks for reading and please refer this article to your friends and colleagues.

Recommendation
Read Working with Roles in ASP.NET Identity for MVC after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: rajeshgajra19889-26855 on: 9/1/2014 | Points: 25
Hello sir how to work with cascade dropdown from database in mvc??
Posted by: Akiii on: 10/9/2014 | Points: 25
Hello sir,

Can postback of dropdownlist via ajax is possible in asp.net mvc ?

Akiii

Login to post response

Comment using Facebook(Author doesn't get notification)