【问题标题】:Templated Helpers and SelectLists in the View Model don't mix: true?View Model 中的模板化 Helpers 和 SelectLists 不混合:是吗?
【发布时间】:2011-09-21 14:00:29
【问题描述】:

在将选择列表的数据源包含在视图模型中时,建议的最佳实践似乎存在脱节。例如,许多最佳实践博客文章都会推荐以下内容:

视图模型:

public class InvoiceViewModel 
{
     [UIHint("SelectInvoiceType")]
     public int idInvoiceType { get; set; }

     /* snip */

     /* I'll use this in the view to generate a SelectList */
     public List<invoicetype> InvoiceTypes { get; set; }
}

但是当我们进入编辑器模板时,Model 对象将只是 int,不知道包含的视图模型:

SelectInvoiceType.cshtml

@model int
@{
  Layout = "~/Views/Shared/_EditorFormItem.cshtml";
  List<SelectListItem> selList = /* nothing to say here, really */;
}
@section DataContent {
   @Html.DropDownListFor(m => Model, selList, null)
}

所以,除非我遗漏了什么,否则这两个“最佳实践”——视图模型中的模板化视图助手和强类型列表数据——只是不能一起使用。您必须将列表数据填充到 ViewBag 中。听起来对吗?

很抱歉听起来难以置信,但我觉得我一定错过了什么。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    您必须求助于将列表数据填充到 ViewBag 中。听起来对吗?

    没有。对我来说,在 ViewBag/ViewData 中塞东西听起来不对。您不应将int 用作应该生成下拉列表的编辑器模板的模型类型。一个下拉列表由两个属性组成:一个标量类型,用于将选定的值绑定到,一个集合用于在此 ddl 中生成不同的选项。

    所以更正确的方法是:

    public class MyViewModel
    {
        [UIHint("SelectInvoiceType")]
        public InvoiceTypesViewModel Invoice { get; set; }
    
        ... some other properties specific to the view
    }
    

    其中InvoiceTypesViewModel 是一个视图模型,并且不包含对域模型的任何引用,例如您的示例列表中的invoicetype

    public class InvoiceTypesViewModel
    {
         public int SelectedInvoiceType { get; set; }
         public SelectList InvoiceTypes { get; set; }
    }
    

    然后在你的主视图中:

    @model MyViewModel
    ...
    @Html.EditorFor(x => x.Invoice)
    

    和编辑器模板:

    @model InvoiceViewModel
    @Html.DropDownListFor(m => m.SelectedInvoiceType, Model.InvoiceTypes)
    

    【讨论】:

    • 原则上我喜欢这个想法。不过,我几乎只使用 object.cshtml 模板,因此每个属性都没有 @Html.EditorFor() 调用。但只要我允许 TemplateDepth >1,这应该可行。
    • 当然,现在 AutoMapper 不会自动将值输入到我的模型中。唉,更多配置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多