Using DropDownList in ASP. NET MVC

Source: Internet
Author: User

In ASP., although we can write HTML controls directly in the page and bind the properties of the control, it is more convenient to use the helper methods in HtmlHelper. In view, it contains a property HTML of type HtmlHelper, which provides a shortcut for us to render the control.

We are mainly here today to discuss the use of html.dropdownlist, starting with Html.textbox.

Html.textbox has an overloaded method as follows:

PublicstaticstringTextBox(thishtmlhelperhtmlhelper,stringname ,objectvalue);             

Where the name parameter is the value of the text box Name property (as well as the ID property), which is the default value of the text box (the value of the Value property). If the value parameter is null or if an overloaded method with no value parameter is used, then the name parameter is also a key value, which is responsible for getting the default value of the text box. Gets the order of whether an item with a key value of name is present from ViewData, and if none is found in ViewData, the property with the name value is returned from Viewdata.model, or null if it still does not exist. (See HtmlHelper Inputhelper Auxiliary method for details)

Other words

PublicActionResultTest(){ViewData["Name"]="Jade";  returnView();}              

<%=Html.  TextBox("Name")%>       

Such a code would output HTML like this:

<inputid="name"name="name"type="text"value= "Jade"/>             

Because the ID of the textbox and the value of the Name property have the same name as an item in ViewData (all name), the value of the TextBox's Values property is automatically bound to the value of the name item in ViewData. Not only is ViewData, if the type of the view model contains the name attribute, it will also output the same result:

var=newUser{Name="Jade"};  ViewData.  Model= user;  returnView();                

If name is present in both ViewData and Viewdata.model, the items in the ViewData are used preferentially.

The same is true for controls such as checkboxes, Hidden, Password, and Rediobutton, which, like the textbox, use the input tag, which is roughly the same as the rules for property binding.

DropDownList is different from controls such as a TextBox, which uses the select tag. It requires two values: the list displayed in the drop-down box, and the default options. Automatic binding can only bind one property at a time, so you need to choose whether to bind the list or the default option.

Each overloaded version of the DropDownList extension method is "basically" passed to this method:

Public Static String DropDownList(This HtmlHelper HtmlHelper, string name , ienumerable< Selectlistitem> Selectlist,string optionlabel, Span class= "Typ" >idictionary<string, object> Htmlattributes)  {  ... }             /span>                

If SelectList is not specified, the method automatically binds the list, that is, the value corresponding to name from ViewData. If SelectList is provided, the default option is automatically bound, which is to find selectedlistitem from SelectList that the selected property is true. (See Selectinternal helper Method for HtmlHelper method)

Example 1: If you have the following code in the action method:

List<SelectListItem>Items= New List<SelectListItem> ();Items.Add(New SelectListItem { Text = "Kirin", Value = "29" });Items.Add(New SelectListItem { Text = "Jade", Value = "28", Selected = trueitems. Add (new selectlistitem  { text  =  "Yao" , value =  "}); this. Viewdata[ "list" ] =< Span class= "PLN" > Items;             

Use this in view:

<%=Html.  DropDownList("list")%>       

Then the helper method will take the lead to get the key to list from ViewData, and if the item is a ienumerable<selectedlistitem> type then bind to the drop-down box, Otherwise, InvalidOperationException will be thrown. Because the second SelectListItem is selected true, the second is selected by default.

Example 2: If the code in the action is as follows:

List<SelectListItem>Items= New List<SelectListItem> ();Items.Add(New SelectListItem { Text = "Kirin", Value = "29" });Items.Add(New SelectListItem { Text = "Jade", Value = "28"});Items.Add(New SelectListItem { text =  "Yao" , value = "}); this. Viewdata[ "list" ] =< Span class= "PLN" > Items;this. Viewdata[ "selected" ]  = 24         

The code in view is as follows:

<%=Html.  DropDownList("selected",ViewData["list"]asIEnumerable<  SelectListItem>)%>             

The helper method binds the viewdata["list" to a drop-down box, and then gets the key to selected from ViewData and sets the value in the list to the value of the item equal to the default selection of the Selectelistitem.

Both of these methods are not a best practice, although they can achieve the correct display of DropDownList. In a real project, we prefer to use strong typing in our code. For example, in the above two cases, the text and value of SelectListItem are originally the name and age properties of the user object, but the code above does not reflect the corresponding relationship. If the user list is obtained from a database or other external resource, do we have to bind it in such a way?

Var Users= Getusers();Foreach (Var UserInch users) { Items. Add (new selectlistitem  { text  = User. Name, value =  User. Age. Tostring ()  });                /span>                

This is clearly beyond our tolerance. So what is best practice?

ASP. NET MVC prepares a secondary type for both the DropDownList and the ListBox (both use the SELECT tag in html): SelectList. SelectList inherits from Multiselectlist, while the latter implements Ienumerable<selectlistitem>. In other words, selectlist can be used directly as the second parameter of the Html.dropdownlist method.

The multiselectlist contains four properties, respectively:

    • Items: The list that appears in the select tag, usually denoted with the option tag. The IEnumerable type.
    • DataTextField: The text item as option, String type.
    • DataValueField: The value item as option, String type.
    • Selectedvalues: The value of the selected item, the IEnumerable type.

Obviously, as a DropDownList, the selected item cannot be IEnumerable, so SelectList provides a new property:

    • SelectedValue: The value of the selected item, the object type.

At the same time, the SelectList constructor is as follows:

Public SelectList(IEnumerable Items, String DataValueField, String datatextfield, object  selectedvalue)  : base (items Datavaluefield, Datatextfield toenumerable (selectedvalue  { selectedvalue< Span class= "PLN" > = Selectedvalue;               /span>                

So our code changes to:

Var Users= getusers (); var selectlist = new selectlist (users,  "age" ,  " Name ", " ); this. Viewdata[ "list" ] =< Span class= "PLN" > Selectlist;            

<%=Html.  DropDownList("list")%>       

Of course, you can also use constructor overloads without the SelectedValue parameter, and explicitly specify Ienumerable<selectlistitem> in view, and in ViewData or view Other items with the same name as DropDownList are specified as default options in model.

Finally, let's review the three uses of DropDownList:

    1. Establishes a ienumerable<selectlistitem> and specifies the default selected item in it.
    2. Establish Ienumerable<selectlistitem>, specify the default selection in the properties of a separate ViewData item or view model.
    3. Use SelectList.

Well, about the usage of DropDownList we discussed here today, will you use it?

Using DropDownList in ASP. NET MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.