The DropDownLists in Asp.net MVC seems to be confusing programmers who initially transferred from Asp.net Forms. This article describes all aspects that you need to know in Asp. Net MVC to use DropDownLists.
DropDownList and ComboBox are generated as html select tags no matter what you call them. between the <select> open tag and </select> closed tag, each list element must be enclosed in the <option> tag. of course, you can also use the <optgroup> label to logically divide each option into different groups. If the value attribute is set for <option>, the Value attribute is the value of the select element when the form is submitted. if you forget to assign a value to the value attribute, the content of the package in the <option> </option> label is the submitted value.
For the sake of simplicity, here I will use a static list as an example. You can add these as html to your View directly:
<select name="year"> <option>2010</option> <option>2011</option> <option>2012</option> <option>2013</option> <option>2014</option> <option>2015</option></select>
Or, add a small amount of dynamic information to the list. If you need to list the Year, the list will be automatically pushed back for one year as the New Year arrives:
<select name="year"> <option><%= DateTime.Now.Year %></option> <option><%= DateTime.Now.AddYears(1).Year %></option> <option><%= DateTime.Now.AddYears(2).Year %></option> <option><%= DateTime.Now.AddYears(3).Year %></option> <option><%= DateTime.Now.AddYears(4).Year %></option> <option><%= DateTime.Now.AddYears(5).Year %></option></select>
It can be even simpler:
<select name="year"> <% for (var i = 0; i < 6; i++){%> <option><%= DateTime.Now.AddYears(i).Year %></option> <%}%></select>
The above three code segments have the same effect, as shown below:
If the data is from the database, it is best to use Html. the DropDownList () extension method creates the DropDownList by using eight overload methods. here I will not describe these different reloads, but will describe the main reloads. First overload-Public static string DropDownList (this HtmlHelper htmlHelper, string name)-Only one string type parameter is accepted. the help document simply illustrates that this string parameter is far from enough for the name attribute of <select>. this parameter is not only the value of the name and id of the <select> element, it is also used to search for elements in ViewData. If the string parameter matches the key of ViewData, The ViewData element is bound with helper to create <option>, the ViewData element type must be a set of SelectListItems. the following code uses linq to SQL TO extract types from the Northwind database. The first overload of the DropDownList extension method is used:
public ActionResult Index(){ var db = new NorthwindDataContext(); IEnumerable<SelectListItem> items = db.Categories .Select(c => new SelectListItem { Value = c.CategoryID.ToString(), Text = c.CategoryName }); ViewData["CategoryID"] = items; return View();}
Note that each SelectListItem object must assign values to the Value and Text attributes. They will match the content between the value Attribute of the html <option> and <option> </option> at runtime. Note that it is a bit strange to use "CategoryID" for the ViewData key, but in fact, the value submitted to the server by CategoryID <select> is actually meaningful to use this name. In View, use the overload method:
<%= Html.DropDownList("CategoryID") %>
The generated HTML is as follows:
<select id="CategoryID" name="CategoryID"> <option value="1">Beverages</option> <option value="2">Condiments</option> <option value="3">Confections</option> <option value="4">Dairy Products</option> <option value="5">Grains/Cereals</option> <option value="6">Meat/Poultry</option> <option value="7">Produce</option> <option value="8">Seafood</option></select>
The second overload method of Html. DropDownList-Public static string DropDownList (this HtmlHelper htmlHelper, string name, IEnumerable <SelectListItem> selectList )-Is frequently used. In this overload, you can use IEnumerable <SelectListItem> or SelectList object as the parameter. First, let's look at the code in the View before returning the methods of the above two objects:
<%= Html.DropDownList("CategoryID", (IEnumerable<SelectListItem>) ViewData["Categories"]) %>
Let's talk about the first object type to store ViewData-IEnumerable <SelectListItem>Object. The code is similar to the previous example:
public ActionResult Index(){ var db = new NorthwindDataContext(); IEnumerable<SelectListItem> items = db.Categories .Select(c => new SelectListItem { Value = c.CategoryID.ToString(), Text = c.CategoryName }); ViewData["Categories"] = items; return View();}
Let's look at the code that stores the SelectList type in ViewData:
public ActionResult Index(){ var db = new NorthwindDataContext(); var query = db.Categories.Select(c => new { c.CategoryID, c.CategoryName }); ViewData["Categories"] = new SelectList(query.AsEnumerable(), "CategoryID", "CategoryName"); return View();}
Using SelectList makes the code in the Controller a little more neat, and of course the same is true in the View. The SelectList constructor has several reloads that can accept objects as parameters to represent the selected options:
public ActionResult Index(){ var db = new NorthwindDataContext(); var query = db.Categories.Select(c => new { c.CategoryID, c.CategoryName }); ViewData["Categories"] = new SelectList(query.AsEnumerable(), "CategoryID", "CategoryName", 3); return View();}
The code above will make "Confections" selected after the list is generated:
Default Value
In all the examples above, the first option is selected by default after the page is loaded. However, in many cases, a default value is required to replace the first value, this default value can be blank or prompt the user to select, or similar. DropDownList also has an overload to implement this-Public static string DropDownList (this HtmlHelper htmlHelper, string name, IEnumerable <SelectListItem> selectList, string optionLabel ).
<%= Html.DropDownList("CategoryID", (SelectList) ViewData["Categories"], "--Select One--") %>
CSS and HTML attributes
The DropDownList has four overloading methods to add HTML attributes after the DropDownList is generated. Two of them accept IDictionary <string, object> as parameters, and the other two use anonymous objects as parameters. The following two pieces of code generate the same html, both adding the CSS selector and binding the client onchange () event:
<%= Html.DropDownList( "CategoryID", (SelectList)ViewData["Categories"], "--Select One--", new Dictionary<string, object> { {"class", "myCssClass"}, {"onchange", "someFunction();"} }) %>
<%=Html.DropDownList( "CategoryID", (SelectList) ViewData["Categories"], "--Select One--", new{ @class = "myCssClass", onchange = "someFunction();" }) %>
You may have noticed that the second Code contains an attribute called @ class, it will still be generated as a "class", but the class is a C # keyword, so you need to add "@" before the attribute name "@", you may wonder why two different loads are required to add tags to html? The use of the anonymous method in the second part of the code is more concise and elegant, of course, the use of the second part of the writing method. However, as mentioned in the description of HTML 5, you can dynamically add custom attributes to html elements. Custom Attributes must start with "data, however, if you try to create a property name in the C # object that contains a hyphen (Translator's note: that is, "-"), the compilation process will be incorrect, so Dictionary <string, object> can be used as a parameter to solve this problem.
Where is AutoPostBack?
In the past, programmers who used web Form development often asked where AutoPostBack went? It is very easy to use IDE and check AutoPostBack. Because it is easy to use, most developers will not think about the mechanism of AutoPostBack. In fact, if you choose AutoPostBack, The DropDownList will be added with an onchange attribute that triggers javascript events, resulting in the form where the DropDownList is located to be submitted. This process must be implemented manually in MVC, but it is also very simple. The code below implements this in two ways. The method in the first code sets html attributes through object as a parameter, another piece of code uses jQuery to achieve the same effect. To put it bluntly, I have written down most of the DropDownList in form. below is the first method:
<% using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "TheForm" })){%> <%= Html.DropDownList( "CategoryID", (SelectList) ViewData["Categories"], "--Select One--", new{ onchange = "document.getElementById('TheForm').submit();" })%><%}%>
The following describes how to use jQuery.
<script type="text/javascript"> $(function() { $("#CategoryID").change(function() { $('#TheForm').submit(); }); });</script><%using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "TheForm" })){%> <%=Html.DropDownList("CategoryID", (SelectList) ViewData["Categories"], "--Select One--") %><%}%>
Prompt
In HtmlHelper, no overload is provided to add a prompt for DropDownList. The prompt is implemented by setting the title attribute in <option>, of course, you can implement your own HtmlHelper to assign corresponding values to each title through the list, but this is a little troublesome. Instead, you can use jQuery to easily achieve this:
<script type="text/javascript"> $(function() { $("#CategoryID option").each(function() { $(this).attr({'title': $(this).html()}); }); });</script>
----------------------------------------------
Link: http://www.mikesdotnetting.com/Article/128/Get-The-Drop-On-ASP.NET-MVC-DropDownLists
Translated by: CareySon