简体   繁体   English

MVC 2:如何使用Html.DropDownListFor?

[英]MVC 2: How to use Html.DropDownListFor?

I'm not exactly sure on my lambda's yet but why isn't the following working? 我不确定我的lambda,但是为什么下面的方法不起作用? 4/mvc2 4 / MVC2

Works: 作品:

// SpotlightsController.cs
public class SpotlightFormViewModel
{

    // props
    public Spotlight Spotlight { get; private set; }
    public SelectList Featured { get; private set; }
    public IDictionary<string, int> feature = new Dictionary<string, int>(){
        {"True", 1},
        {"False", 0},
    };

    // constr
    public SpotlightFormViewModel(Spotlight spotlight)
    {
        Spotlight = spotlight;
        Featured = new SelectList(feature.Keys, spotlight.Featured);
    }
}

// Edit.aspx
<div class="editor-label">
    <label for="Featured">Featured:</label>
</div>
<div class="editor-field">
    <%: Html.DropDownList("Featured", Model.Featured)%>
    <%: Html.ValidationMessage("Featured") %>
</div>

Doesn't work: 不起作用:

// Compiler Error Message: CS1501: No overload for method 'DropDownListFor' takes 1 arguments
// Edit.aspx
<div class="editor-label">
    <%: Html.LabelFor(model => model.Featured) %>
</div>
<div class="editor-field">
    <%: Html.DropDownListFor(model => model.Featured)%>
    <%: Html.ValidationMessageFor(model => model.Featured) %>
</div>

DropDownListFor takes (at least) two arguments. DropDownListFor接受(至少)两个参数。 The first argument is the property that will hold the selected value on postback (and contains the current selected value) and the second is an IEnumerable<SelectListItem> containing the key/value pairs for the options. 第一个参数是将在回发时保留所选值的属性(并包含当前所选值),第二个参数是IEnumerable<SelectListItem>其中包含选项的键/值对。 Rename your Feature property to FeatureMenu or something and create a property name Featured of the type corresponding to the option's value. 将Feature属性重命名为FeatureMenu或其他名称,然后创建与选项的值相对应的类型的属性名称Featured。 Then add the FeatureMenu to the DropDownListFor's arguments. 然后将FeatureMenu添加到DropDownListFor的参数中。

 public SelectList FeatureMenu { get; private set; }
 public string Featured { get; private set; }

... ...

 <%: Html.DropDownListFor( model => model.Featured, Model.FeatureMenu ) %>

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

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