代码之家  ›  专栏  ›  技术社区  ›  ryan

MVC 2:如何使用Html.DropDownListFor?

  •  2
  • ryan  · 技术社区  · 14 年前

    我还不能完全确定我的lambda,但是为什么下面的方法不起作用呢?4/mvc2型

    作品:

    // 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>
    

    // 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>
    
    1 回复  |  直到 14 年前
        1
  •  5
  •   tvanfosson    14 年前

    DropDownListFor 接受(至少)两个参数。第一个参数是将在回发时保存选定值(并包含当前选定值)的属性,第二个参数是 IEnumerable<SelectListItem> 包含选项的键/值对。将功能属性重命名为FeatureMenu或其他内容,并创建与选项值对应的类型的功能属性名称。然后将FeatureMenu添加到DropDownListFor的参数中。

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

    ...

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