Binding DropDownList Using Html.DropdownListFor In ASP.Net MVC

In this article we will learn how to bind dropdownlist using Html.DropdownListFor in MVC with the help of model class.
In my previous article we have learned how to bind simple dropdownlist with the help of SelectListItem class.Read previous article
What is Html.DropdownListFor ?
Html.DropdownListFor is the strongly typed html helper to bind the dropdownlist .
So let us start step by step
Step 1 : Create an MVC application
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
  3. Choose MVC empty application option and click on OK
Step 2 : Create Model Class
Right click on Model folder in the created MVC application, give the class name EmpModel or as you wish and click OK.
EmpModel.cs
public class EmpModel
    {
        public int Value { get; set; }
        public string Text { get; set; }
       
    }
In the above model class we have created two properties
  • Value : For DropdownList value  
  • Text : For DropdownList Text
Step 3 : Add controller class
Right click on Controller folder in the created MVC application ,give the controller class name Home or as you  wish and click on OK then write the following code
HomeController.cs
public ActionResult Index()
        {
            //using emp model class
            List<EmpModel> ObjItem = new List<EmpModel>()
            {

            new EmpModel {Text="Select",Value=0},
            new EmpModel {Text="ASP.NET",Value=1 },
            new EmpModel {Text="C#",Value=2},
            new EmpModel {Text="MVC",Value=3},
            new EmpModel {Text="SQL",Value=4},
            };
            ViewBag.ListItem = ObjItem;

            return View();
        }
In the above code ,We have added items in list  and saved into the ViewBag.
Step 4 : Add View
Right click on the solution explorer of our created project and add the empty view. Now write the following code into the created view.

@model BindingDropDownList.Models.EmpModel
@{
    ViewBag.Title = "www.compilemode.com";
}
<div style="margin-top:20px">
    @Html.DropDownListFor(ddl => ddl.Value,
                        new SelectList(ViewBag.ListItem, "Value", "Text"))

</div>

Now run the application the output will be look like as follows

 
Note 
  • In the above example database is not used however you can bind the generic list from database.
If you wants to learn more about MVC then please refer following section
Summary
I hope this article is useful for all the readers. If you have any suggestion please contact me.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode