【问题标题】:MVC 2: How to use Html.DropDownListFor?MVC 2:如何使用 Html.DropDownListFor?
【发布时间】:2010-07-13 19:52:44
【问题描述】:

我还不确定我的 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>

【问题讨论】:

    标签: c# asp.net-mvc-2


    【解决方案1】:

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

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

    ...

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

    【讨论】:

    • 谢谢它的工作。但看起来现在我只需要解决描述的 DDL 错误 stackoverflow.com/questions/1916462/…
    • 嗯。我还没有看到那个特定的问题,但是我通常使用自定义方法来返回视图,以确保根据我返回的视图填充菜单。
    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多