当前位置 : 主页 > 网络编程 > ASP >

asp.net-mvc – 编辑器在没有@foreach的情况下不渲染可枚举

来源:互联网 收集:自由互联 发布时间:2021-06-24
这是令人费解的.为简单起见,想象一下具有.Employees可枚举属性的Company实体.我已经在其他地方看到,使EditorTemplates能够合理地呈现可枚举的技巧是使用这样的语法: 在Index.cshtml中: @Htm
这是令人费解的.为简单起见,想象一下具有.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")
}

此构造也无法发布company.Employees集合回到我的其他控制器操作.

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

>在列表中为每个实例渲染具有唯一ID的子集合
>使用模型发回子集合

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

Per @ David-Tansey(从 this answer开始 – 请参阅更详细的解释):

(改为适合这个问题):

When you use @Html.EditorFor(c => c.Employees) MVC convention chooses the default template for IEnumerable. This template is part of the MVC framework, and what it does is generate Html.EditorFor() for each item in the enumeration. That template then generates the appropriate editor template for each item in the list individually – in your case they’re all instances of Employee, so, the Employee template is used for each item.

总结他对你使用命名模板的解释,你实际上是在传递整个IEnumerable< Employee>通过使用@ Html.EditorFor(company => company.Employees,“EmployeeEditorTemplate”)来预期单个Employee的模板.

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

网友评论