简体   繁体   English

HTML.DropDownListFor中的第一个参数的用途是什么?

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

I'm reading the documentation on HTML.DropDownListFor and it states the following: 我正在阅读HTML.DropDownListFor上的文档,它指出以下内容:

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: SiteList是:

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? 我不明白示例中lambda的目的是什么以及如何在输出中使用它?

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. 这意味着当表单回发时,那么Selected属性将在列表中具有所选项目的值。

See the html generated by the three expression. 请参见由三个表达式生成的html。 The name and id would be different in all the cases. 在所有情况下,名称和ID都将不同。 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. 这些名称是在将所选值绑定到模型的属性时使用的。元素的名称应与发布页面时将所选值投标的属性的名称相同。为元素命名以达到目的的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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