asp.net-mvc - EditorFor 在没有 @foreach 的情况下不呈现 ienumerable

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

这比较莫名其妙。为简单起见,想象一个具有 .Employees 可枚举属性的公司实体。我在 SO 的其他地方看到,让 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 ...表明模型绑定(bind)器足够聪明,可以动态计算绑定(bind)并索引可枚举。我得到了不同的结果(如果 modelbinder 不应该如此神奇,这正是我所期望的):
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 集合发布回我的其他 Controller 操作。

关于实现以下目标需要什么的任何想法?
  • 使用列表中每个实例的唯一 ID 渲染子集合
  • 用模型
  • 将子集合发布回来

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

    最佳答案

    根据@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>到一个需要单个 Employee 的模板通过使用 @Html.EditorFor(company => company.Employees, "EmployeeEditorTemplate") .

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

    关于asp.net-mvc - EditorFor 在没有 @foreach 的情况下不呈现 ienumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18005070/

    相关文章:

    c# - MVC 3 发送类 JSON

    jQuery ajax 在asp.net mvc 中上传文件

    jQuery Ajax : Reference MVC controller url from App root

    c# - 带有包装器的自定义 TextBox Asp.net MVC Helper

    c# - 文件/图像上传后 ASP.NET 3.0 mvc 应用程序崩溃

    c# - 在运行时动态生成 Razor View ?

    c# - Url 验证属性将 `localhost` 标记为无效 Url

    c# - 来自时区分钟偏移量的 TimeZoneInfo

    asp.net-mvc-4 - 在 SignalR Hub 中生成路由 URL

    inversion-of-control - IoC (spring.net) 与 asp.net - ctor 在 Controller 上注入(inject)非单例对象 - 我在哪里处理?