How to Create DropDownList in Asp.Net MVC

Drop down list is a common and usable control in every programming area to let the user can select only one item from the list. In MVC we have to create a list in action method of controller and then pass it through any method like ViewBag and ViewModel etc.

Programmer can create required type of list as per the requirements, we will create a SelectListItem type of list because this list provides two property Text and Value by default. Create a simple list of type SelectListItem and add some items (we have added four item here) as added below:

List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Value 1", Value = "1" });
items.Add(new SelectListItem { Text = "Value 2", Value = "2" });
items.Add(new SelectListItem { Text = "Value 3", Value = "3" });
items.Add(new SelectListItem { Text = "Other", Value = "4" });

Now to pass this to View page write a single line as written below:

ViewBag.ddlItems = new SelectList(items, "Value", "Text");

Value will be the dataValue field and Text will be dataText field for this dropdownlist. In the view page create a form and of course a dropdownlist with a submit button:

@using (Html.BeginForm())
        @Html.DropDownList("selectedItem", (IEnumerable<SelectListItem>)ViewBag.ddlItems)
        <input type="submit" value="Submit" id="submitBtn" />

First parameters of this helper Html.DropDownList() specifies name of the HTML select element, and also the name of the view model property that is bound to the element. Second parameter shows the list of options of select list.

This will create a dropdownlist with a submit button. Run the application and open particular view in the browser. Select any value and then submit. Oops! i haven't write the code to access the selected value. So write HttpPost type of action:

public ActionResult Index(string selectedItem)

Here parameter selectedItem is the same name of dropdownlist we have assigned in the view page. Again run the application, select any value("Value 2") and then submit. This parameter will contain the selected value(2).


Post a Comment

Popular posts from this blog

difference between structure and union in C Language

Difference between Linear search and Binary Search in c language

Difference between static and dynamic websites