编辑器在没有@foreach的情况下不渲染可枚举

时间:2013-08-01 21:37:18

标签: asp.net-mvc asp.net-mvc-4 razor mvc-editor-templates

这令人费解。为简单起见,想象一下具有.Employees可枚举属性的Company实体。我已经在其他地方看到了使得EditorTemplates能够合理地呈现可枚举的技巧是使用这样的语法:

在Index.cshtml中:

@Html.EditorFor(company => company.Employees, "EmployeeEditorTemplate") 

EmployeeEditorTemplate.cshtml需要一名员工

@model MyNamespace.Models.Employee
//...
@Html.EditorFor(x => x.FullName)
// ...etc.

像这样的帖子:Viewmodels List Is Null in Action ...表示模型绑定器足够智能,可以找出绑定并动态索引可枚举。我得到了不同的结果(正如我所期望的那样,如果模型绑定器不应该是如此mageriffic):

The model item passed into the dictionary is of type 
System.Collections.Generic.List`1[MyNamespace.Models.Employee]', 
but this dictionary requires a model item of type 
'MyNamespace.Models.Employee'.

自己枚举它会使集合很好,但是为每一行的控件发出相同的id(当然,这不是最佳的,但它告诉我EditorTemplate在功能上是正确的):

@foreach (var item in Model.Employees)
{
    @Html.EditorFor(x => item, "EmployeeEditorTemplate")
}

此构造也无法发布公司。员工集合回到我的其他控制器操作。

有关实现以下目标所需要的任何想法?

  • 使用列表中的每个实例呈现具有唯一ID的子集合
  • 使用模型
  • 发布子集合

我不在乎我是否必须自己列举它,也不在于它是在EditorTemplate内部还是外部;我刚刚看到它说这是不必要的,如果你让它处理事情,MVC会更好。感谢。

3 个答案:

答案 0 :(得分:5)

Per @ David-Tansey(来自this answer - 请参阅更详细的说明):

(已更改为适合此问题)

  

当您使用@Html.EditorFor(c => c.Employees)时,MVC约定会为IEnumerable选择默认模板。此模板是MVC框架的一部分,它的作用是为枚举中的每个项生成Html.EditorFor()。然后,该模板为列表中的每个项目单独生成相应的编辑器模板 - 在您的情况下,它们都是Employee的实例,因此,Employee模板用于每个项目。


总结他对您使用命名模板的解释,实际上,您使用IEnumerable<Employee>将整个Employee传递给期望单@Html.EditorFor(company => company.Employees, "EmployeeEditorTemplate")的模板。

注意:我真的只回答了这个问题,因为它没有答案,我先在这里跌跌撞撞。至少现在有人不会关闭它,可能会错过答案而不必经历获得重复问题投票的严峻考验,等等等等。

答案 1 :(得分:1)

您可以在此处阅读:Hanselman's article

简而言之,您应该在您的视图中写入(index.cshtml):

int i=0;
@foreach (var item in Model.Employees)
{
   @Html.TextBox(string.Format("Model[{0}].FullName", i), item.FullName)
   i++;
}

答案 2 :(得分:1)

foreach可与@HTML.EditorFor一起使用,例如,请参阅以下语法:

@foreach(var emp in @Model)
{ 
    @Html.EditorFor(d => emp.EmployeeName)
    @Html.EditorFor(d => emp.Designation)
    <br />
}
相关问题