Use DropDownList in ASP. NET MVC

Source: Internet
Author: User

In ASP. net mvc, although we can directly write HTML controls on the page and bind them with attributes, it is more convenient to use the auxiliary methods in HtmlHelper. The View contains an Html attribute of the HtmlHelper type, which provides shortcuts for rendering controls.

Today we will mainly discuss the usage of Html. DropDownList, starting with Html. TextBox.

Html. TextBox has an overload method in the following format:

Public static string TextBox (this HtmlHelper htmlHelper, string name, object value); where the name parameter is the value of the text box name attribute (and id attribute, the value parameter is the default value of the text box (that is, the value of the value Attribute ). If the value parameter is null or the overload method without the value parameter is used, the name parameter is also a key value and obtains the default value of the text box. The obtained order is: first, check whether there is an item with a key value of name in ViewData. If ViewData does not exist, then view data. check whether the property named name exists in the Model. If the property still does not exist, null is returned. (For details, refer to the HtmlHelper InputHelper auxiliary method)

That is to say

Public ActionResult Test ()
{
ViewData ["Name"] = "Jade ";
Return View ();
}
<% = Html. TextBox ("Name") %> such code will output such HTML:

<Input id = "Name" name = "Name" type = "text" value = "Jade"/>
Because the value of the TextBox's id and name attributes has the same Name as one of ViewData, the value of the TextBox's value attribute is automatically bound to the value of the Name item in ViewData. Not only ViewData, but if the view model type contains the Name attribute, the same result will be output:

Var user = new User {Name = "Jade "};
ViewData. Model = user;
Return View ();
If Name exists in both ViewData and ViewData. Model, the items in ViewData are preferentially used.

The same is true for controls such as CheckBox, Hidden, Password, and RedioButton. They all use the input tag like TextBox, and the rules for property binding are roughly the same.

DropDownList is different from TextBox and other controls. It uses the select flag. It requires two values: the list displayed in the drop-down box and the default options. Automatic Binding can only bind one attribute at a time. Therefore, you need to select the binding list or the default option as needed.

Each overload 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,
IDictionary <string, object> htmlAttributes ){
...
}
If selectList is not specified, this method will automatically bind the list, that is, find the value corresponding to name from ViewData. If selectList is provided, the default option is automatically bound, that is, the SelectedListItem with the Selected Attribute true is found from selectList. (For details, see the SelectInternal auxiliary method of the HtmlHelper method)

Example 1: If the Action method contains the following code:

List <SelectListItem> items = new List <SelectListItem> ();
Items. Add (new SelectListItem {Text = "Kirin", Value = "29 "});
Items. Add (new SelectListItem {Text = "Jade", Value = "28", Selected = true });
Items. Add (new SelectListItem {Text = "Yao", Value = "24 "});
This. ViewData ["list"] = items; used in View as follows:

<% = Html. dropDownList ("list") %> the auxiliary method first obtains the item whose key is list from ViewData. If the item is IEnumerable <SelectedListItem>, it is bound to the drop-down box, otherwise, InvalidOperationException is thrown. Because the Selected of the second SelectListItem is true, the second item 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 = "24 "});
This. ViewData ["list"] = items;
This. ViewData ["selected"] = 24; the Code in View is as follows:

<% = Html. dropDownList ("selected", ViewData ["list"] as IEnumerable <SelectListItem>) %> the auxiliary method binds ViewData ["list"] to a drop-down box, obtain the items whose key is selected from ViewData, and set the SelecteListItem with the same Value as the Value of the item in the list to the selected item by default.

Although the above two methods can achieve the correct display of DropDownList, it is not the best practice. In actual projects, we prefer to use a strong type in the code. For example, in the above two examples, the Text and Value of SelectListItem are the Name and Age attributes of the User object, but the above Code does not reflect this ing. If the User list is obtained from the database or other external resources, do we need to bind it in this way?

Var users = GetUsers ();
Foreach (var user in users)
{
Items. Add (new SelectListItem {Text = user. Name, Value = user. Age. ToString ()});
} This is obviously intolerable. So what is best practice?

ASP. net mvc provides a secondary type: SelectList for DropDownList and ListBox (both use the select mark in html. SelectList is inherited from MultiSelectList, which implements IEnumerable <SelectListItem>. That is to say, SelectList can be directly used as the second parameter of the Html. DropDownList method.

MultiSelectList contains four attributes:

Items: list used in the select tag, which is usually indicated by the option tag. IEnumerable type.
DataTextField: Specifies the text item of option, which belongs to the string type.
DataValueField: Specifies the value of option, which belongs to the string type.
SelectedValues: value of the selected item, IEnumerable type.
Obviously, as DropDownList, the selected item cannot be IEnumerable, so SelectList provides a new attribute:

SelectedValue: value of the selected item, object type.
Meanwhile, the SelectList constructor is as follows:

Public SelectList (IEnumerable items, string dataValueField, string dataTextField, object selectedValue)
: Base (items, dataValueField, dataTextField, ToEnumerable (selectedValue )){
SelectedValue = selectedValue;
}
So our code becomes:

Var users = GetUsers ();
Var selectList = new SelectList (users, "Age", "Name", "24 ");
This. ViewData ["list"] = selectList;
<% = Html. DropDownList ("list") %>
Of course, you can also use the constructor overload without the selectedValue parameter, while explicitly specifying IEnumerable <SelectListItem> In the view, specify other items with the same name as DropDownList in ViewData or view model as the default option.

Finally, let's review three usage methods of DropDownList:

Create an IEnumerable <SelectListItem> and specify the default option.
Create an IEnumerable <SelectListItem> and specify the default selected items in the properties of the ViewData item or view model.
Use SelectList.
Okay. We will discuss the usage of DropDownList today. will you use it?

Related Article

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.