There are many ways to bind dropdownlist in MVC ,In this article we will learn how to bind simple dropdownlist using SelectListItem class.So let us learn in brief about SelectListItem class
What is SelectListItem Class ?
SelectListItem is a class which represents the selected item in an instance of the System.Web.Mvc.SelectList class
It has following properties
Create the MVC application ,if you don't know how to create MVC application then please refer my previous articles .
How hope you have did that ,now write the following code into the controller to bind SelectListItem Class as generic list.
In the above code ,I have added items in SelectedListItem Class as List and saved into the ViewBag.
Now open the Index.cshtml view and write the following code
In the above code ,we have passed the Viewbag name as string to the Html helper dropdownlist ,now run the application the output will be look like as follows
SummaryWhat is SelectListItem Class ?
SelectListItem is a class which represents the selected item in an instance of the System.Web.Mvc.SelectList class
It has following properties
- Text :It represent the any text
- Value : Its is the value against the particular text
- Group : Group of items in single element .
- Disabled : Whether the selection item is disabled or not,default is false
- Selected: Decides whether the item in list by default selected or not ,the default is false.
Create the MVC application ,if you don't know how to create MVC application then please refer my previous articles .
How hope you have did that ,now write the following code into the controller to bind SelectListItem Class as generic list.
public class HomeController : Controller { // GET: Home public ActionResult Index() { List<SelectListItem> ObjItem = new List<SelectListItem>() { new SelectListItem {Text="Select",Value="0",Selected=true }, new SelectListItem {Text="Latur",Value="1" }, new SelectListItem {Text="Mumbai",Value="2"}, new SelectListItem {Text="Pune",Value="3"}, new SelectListItem {Text="Delhi",Value="4" }, }; ViewBag.ListItem = ObjItem; return View(); } }
Now open the Index.cshtml view and write the following code
@Html.DropDownList("ListItem")
I hope this article is useful for all the readers. If you have any suggestion please contact me.
Post a Comment