【问题标题】:SelectList with MVC2 and custom ViewModel带有 MVC2 和自定义 ViewModel 的 SelectList
【发布时间】:2010-08-24 06:39:52
【问题描述】:

我创建了一个自定义 ViewModel,其中一个字段是 SelectList/DropDownlist。我想使用 EditorForModel 来显示 ViewModel。除 SelectList 外,所有字段均有效。我尝试了一些不同的东西,但没有任何结果。我在一篇文章中看到 EditorForModel 没有“足够聪明”来执行 DropDownList,我想知道这是否属实。 EditorForModel 更容易使用,输入更少:)

谢谢!

更新

我想通了。我最终做的是使用 UIHint("TemplateName") 并在 EditorTemplates 文件夹中创建了一个 .ascx 文件,输出符合我的预期。

【问题讨论】:

    标签: asp.net-mvc-2 viewmodel selectlist


    【解决方案1】:

    在您的视图模型中,您应该有一个IEnumerable<SelectListItem>

    public IEnumerable<SelectListItem> Months { get; set; }
    

    而在aspx中,需要如下绑定:

    <%
        var htmlAttributes = new Dictionary<string, object> { { "data-autopostback", "true" } }; 
    %>
    
    <%:Html.DropDownList("Month", Model.Months, "-- All --", htmlAttributes)%>
    

    您需要确保在将 Months 属性传递给视图之前填充它。

    如果您需要代码来填充 Months 属性,请告诉我。

    【讨论】:

    • 我认为你错过了我的观点。我想尝试使用 EditorForModel(),这意味着我不必使用 Html.DropDownList。这就是我想弄清楚的可能。
    • 如果您在 ViewModel 中有 IEnumerable 您将如何取回所选值?因为在表单上你会得到一个字符串[],其中包含此属性的选定键
    • Omu,在控制器获取选中值的方法中,参数应该命名为Month。不过,我还没有测试过它的多选下拉菜单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多