【问题标题】:How to create an EditorFor a collection and avoid doing a loop如何创建 EditorFor 集合并避免循环
【发布时间】:2013-01-31 20:19:37
【问题描述】:

例如:

型号

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string  LastName { get; set; }
}

人物编辑器模板 (PersonEditor.cshtml):

@model MvcApplication1.Models.Person

@Html.HiddenFor(x=>x.ID)
<label>First Name</label>    
@Html.TextBoxFor(x=>x.FirstName)
<label>Last Name</label>    
@Html.TextBoxFor(x=>x.LastName)
<br />

在我的主页上,我希望能够执行以下操作:

@model IList<MvcApplication1.Models.Person>

@using (Html.BeginForm())
{       
    @Html.EditorFor(x=>x,"PersonEditor")    
}

并拥有表单中的所有元素,自动生成专有名称;而不必像现在这样遍历集合:

@using (Html.BeginForm())
{
    for (int i = 0; i < Model.Count; i++)
    {
        @Html.EditorFor(x=>Model[i],"PersonEditor")    
    }   
}

表单元素必须包含以下格式:

<input name="[0].ID" type="text" value="Some ID" />
<input name="[0].FirstName" type="text" value="Some value" />
<input name="[1].ID" type="text" value="Some x" />
<input name="[1].FirstName" type="text" value="Some y" />

等等……

因为在我的控制器中,我希望在表单发布打包时收到IList&lt;Person&gt;

我可以完全消除那个 for 循环吗?

编辑

现在,当我简单地执行@Html.EditorFor(x=&gt;x)(换句话说,没有循环)时,我得到了这个异常:

传入字典的模型项是类型 'MvcApplication1.Models.Person[]',但是这个字典需要一个 'MvcApplication1.Models.Person' 类型的模型项。

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-4 razor-2


【解决方案1】:

您应该能够为IEnumerable&lt;T&gt;T 使用相同的模板。模板足够智能,可以枚举 IEnumerable,但您需要重命名编辑器模板以匹配类型名称。那么你应该可以使用

@model IList<MvcApplication1.Models.Person>

@using (Html.BeginForm())
{       
    @Html.EditorForModel()    
}

不幸的是,看起来除了类型名称以外的任何名称的模板都会引发异常

传入字典的模型项是类型 'MvcApplication1.Models.Person[]',但是这个字典需要一个 'MvcApplication1.Models.Person' 类型的模型项

【讨论】:

  • 使用@Html.EditorForModel()怎么样?你有同样的问题吗?
  • 那时我一定是在做一些愚蠢的事情,因为当我这样做时 @Html.EditorFor(x=&gt;x) 我得到了这个异常:The model item passed into the dictionary is of type 'MvcApplication1.Models.Person[]', but this dictionary requires a model item of type 'MvcApplication1.Models.Person'.
  • 是的,和以前一样的例外:The model item passed into the dictionary is of type 'MvcApplication1.Models.Person[]', but this dictionary requires a model item of type 'MvcApplication1.Models.Person'
  • 我的错。我刚刚运行了一个演示来测试它,你是对的。看起来框架中的不一致就像您将 EditorTemplate 名称更改为 Person 并简单地使用 @Html.EditorForModel() 您将获得预期的结果。所以看起来它不适用于非默认命名模板名称。将更新答案。
  • 感谢您的回答。这很有帮助。我不知道模板名称必须与模型名称完全匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多