简体   繁体   中英

What is the use of the first parameter in HTML.DropDownListFor?

I'm reading the documentation on HTML.DropDownListFor and it states the following:

public static MvcHtmlString DropDownListFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    IEnumerable<SelectListItem> selectList
)

What does the expression do? I've been reading and it says to bind it to a property?

I've used the following code:

 @(Html.DropDownListFor(x => x.SiteList[0], new SelectList(Model.SiteList, "LocationID", "Description",Model.SiteList[5].LocationID)))

and that code works just as fine as:

 @(Html.DropDownListFor(x => x.SiteList[0].LocationID, new SelectList(Model.SiteList, "LocationID", "Description",Model.SiteList[5].LocationID)))

and

@(Html.DropDownListFor(x => x.SiteList[0].Description, new SelectList(Model.SiteList, "LocationID", "Description",Model.SiteList[5].LocationID)))

where SiteList is a:

List<Site>

with Site being:

public class Site {
    public string LocationID;
    public string Description;
}

I don't understand what the purpose of the lambda is in the example and how it's being used in the output?

So you would normally have a separate property on your model for this next to your list. When you select a value from the list it sets the property that this is bound to.

class ListType{
    public string Key { get; set; }
    public string Value { get; set; }
}    

class ViewModel{
     public IEnumerable<SelectListItem> List { get; set; } //This is generated from a list of ListType objects
     public string Selected { get; set; }
}

Then you can use:

@Html.DropDownListFor(x => x.Selected, Model.List)

This means when the form is posted back then the Selected property has the value of your selected item in the list.

See the html generated by the three expression. The name and id would be different in all the cases. These name is used while binding the selected value to the property of the model.The name of the element should be same as the name of the property to which the selected value is to be bidden upon posting of the page.The expression gives a friendly way to give name to the element to achieve the purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM