asp.net mvc using DropDownList

Source: Internet
Author: User
Tags bind

In asp.net mvc, although we can write HTML controls directly in the page and bind the properties of the controls, 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 in the form of the following:

public static string TextBox (this htmlhelper htmlhelper, string name, object value);
Where the name parameter is the value of the text box Name property (and ID property), the value parameter is the default value of the text box (that is, the value of the Value property). If the value parameter is NULL or uses an overloaded method without the value parameter, then the name parameter is also a key value, which is responsible for getting the default value of the text box. The order to get is to find out from the ViewData if there is an item with a key value of name value, or null if it does not exist, if there is no property in the ViewData from the Viewdata.model that has a name value. (See HtmlHelper Inputhelper Auxiliary method specifically)

Other words

Public ActionResult Test ()
{
viewdata["Name"] = "Jade";
return View ();
}
<%= Html.textbox ("Name")%>
Such a code would output such HTML:

<input id= "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 the ViewData, the value of the textbox is automatically bound to the value of the name item in ViewData. Not only is ViewData, if the type of view model contains the Name property, the same result will be output:

var user = new User {Name = ' Jade '};
Viewdata.model = user;
return View ();
If name is present in both ViewData and Viewdata.model, the items in ViewData are used preferentially.

The same is true for controls such as CheckBox, Hidden, Password, and Rediobutton, which use the input tag as well as the textbox, and the rules for property bindings are roughly the same.

DropDownList, unlike a TextBox and other controls, uses a select tag. It requires two values: the list displayed in the dropdown 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 as needed.

The overloaded versions of the DropDownList extension method are "basically" passed on to this method:

The public static string DropDownList (this HtmlHelper htmlhelper,
String name,
Ienumerable<selectlistitem> SelectList,
String Optionlabel,
Idictionary<string, object> htmlattributes) {
...
}
If SelectList is not specified, the method automatically binds the list, which is to find the value of name in ViewData. If SelectList is provided, the default option is automatically bound, that is, the Selectedlistitem that selected property is True is found from SelectList. (See the Selectinternal auxiliary method of the HtmlHelper method specifically)

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 = "n", Selected = true});
Items. ADD (new SelectListItem {Text = "Yao", Value = "24"});
This. viewdata["List" = items;
Use this in view:

<%=html.dropdownlist ("list")%>
Then the helper method will take the lead from the ViewData to get the key list item, and if the item is ienumerable<selectedlistitem> type, bind to the Drop-down box. Otherwise the InvalidOperationException will be thrown. Because the second SelectListItem selected is true, the second is selected by default.

Example 2: If the action has 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"});
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 helper method binds viewdata["list" to a drop-down box, then gets the item selected from the ViewData, and sets the value of the following list equal to the value of the item as the default check.

Both of these methods, although they can achieve the correct display of DropDownList, are not best practices. In the actual project, we would prefer to use strong typing in our code. For example, in the previous two cases, SelectListItem's text and value would have been the name and age attribute of the user object, but the code above did not show this correspondence at all. If the user list was obtained from a database or other external resource, would we be bound in this way?

var users = Getusers ();
foreach (var user in users)
{
Items. ADD (new SelectListItem {Text = user. Name, Value = user. Age.tostring ()});
}
This is clearly beyond our tolerance. So what is best practice?

asp.net mvc prepares a secondary type for the DropDownList and the listbox (both using 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: A list that appears in the select tag, usually indicated with the option tag. IEnumerable type.
DataTextField: The text item as option, String type.
DataValueField: As the value item of option, String type.
Selectedvalues: The value of the selected item, IEnumerable type.
Obviously, as a DropDownList, the selected item is not likely to be IEnumerable, so SelectList provides a new property:

SelectedValue: The value of the selected item, type Object.
At the same time, the SelectList constructor looks like this:

Public SelectList (IEnumerable items, string DataValueField, String DataTextField, Object SelectedValue)
: Base (items, DataValueField, DataTextField, toenumerable (SelectedValue)) {
SelectedValue = SelectedValue;
}
So our code changes to:

var users = Getusers ();
var selectlist = new SelectList (Users, "age", "Name", "24");
This. viewdata["List"] = SelectList;
<%=html.dropdownlist ("list")%>

Of course, you can also use a constructor overload with no SelectedValue parameter, and explicitly specify Ienumerable<selectlistitem> in view, and in ViewData or view Model specifies other items with the same name as DropDownList as the default option.

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

Establishes the ienumerable<selectlistitem> and specifies the default selection in it.
Creates a ienumerable<selectlistitem>, specifying a default check in the properties of a separate ViewData item or view model.
Use SelectList.
This is the end.

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.