In this article we will learn how to bind dropdownlist using Model Class in MVC
In my previous article we have learned how to bind simple dropdownlist with the help of SelectListItem class.
Now in this article we are going to see how to bind dropdownlist using Model class
Its a class file in MVC same as other class file were the business logic and validations are written .
So let us start step by step
In the above model class we have created two properties
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
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.
In my previous article we have learned how to bind simple dropdownlist with the help of SelectListItem class.
Now in this article we are going to see how to bind dropdownlist using Model class
Its a class file in MVC same as other class file were the business logic and validations are written .
So let us start step by step
Step 1 : Create an MVC application
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "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.
- Choose MVC empty application option and click on OK
Right click on Model folder in the created MVC application, give the class name EmpModel or as you wish and click OK.
EmpModel.cspublic class EmpModel { public int Value { get; set; } public string Text { get; set; } }
- Value : For DropdownList value
- Text : For DropdownList Text
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(); }
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>
Note
- In the above example database is not used however you can bind the generic list from database.
Summary
I hope this article is useful for all the readers. If you have any suggestion please contact me.
I hope this article is useful for all the readers. If you have any suggestion please contact me.
Post a Comment