[英]ASP.NET MVC EditorTemplate for IEnumerable
I have a model with 2 properties: string
and IEnumerable<SomeModel>
. 我有一个具有2个属性的模型: string
和IEnumerable<SomeModel>
。 If I specify editortemplate by UiHint
for string
, it is applied. 如果我通过UiHint
为string
指定editortemplate, UiHint
其应用。 But when I specify it for IEnumerable<SomeModel>
property, nothing happens. 但是,当我为IEnumerable<SomeModel>
属性指定它时,什么也没发生。 Is there anything special that I need to do for IEnumerable? 我对IEnumerable有什么特别的需要吗?
If I understand your question correctly, you need to replace your IEnumerable
with IList
and then use the following approach: 如果我正确理解了您的问题,则需要用IList
替换IEnumerable
,然后使用以下方法:
public class OrderDTO
{
...
public IList<OrderLineDTO> Lines { get; set; }
...
}
public class OrderLineDTO
{
public int ProductID { get; set; }
...
[Range(0, 1000)]
public int Quantity { get; set; }
...
}
...
@for (int i = 0; i < Model.Lines.Count; ++i)
{
...
@Html.EditorFor(x => x.Lines[i].Quantity)
...
}
...
Works with MVC 4. 适用于MVC 4。
Your HintTemplate model should be IEnumerable<SomeModel>
(you will be iterating the model in the editor template). 您的HintTemplate模型应为IEnumerable<SomeModel>
(您将在编辑器模板中迭代该模型)。 Alternatively instead of UIHint annotation you can use the EditorFor on the collection property (in this case EditorTemplate model will be SomeModel; there is no iteration involved in the view syntax). 另外,也可以在集合属性上使用EditorFor来代替UIHint批注(在这种情况下,EditorTemplate模型将为SomeModel;视图语法中不涉及迭代)。 I've provided a similar reply in this post 我在这篇文章中提供了类似的回复
If your Model looks like 如果您的模型看起来像
public class TestModel
{
public string ParentName { get; set; }
[UIHint("HintTemplate")]
public IEnumerable<TestChildModel> children { get; set; }
}
ChildModel 子模型
public class TestChildModel
{
public int id { get; set; }
public string ChildName { get; set; }
}
Your HintTemplate.cshtml should look like 您的HintTemplate.cshtml应该看起来像
@model IEnumerable<MVC3.Models.TestChildModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>HintTemplate</title>
</head>
<body>
@foreach(var a in Model)
{
<div style="background-color:#4cff00">
@Html.DisplayFor(m => a.ChildName)
@Html.EditorFor(m => a.ChildName)
</div>
}
</body>
</html>
Your view 您的看法
@model MVC3.Models.TestModel
@{
ViewBag.Title = "Test";
}
<h2>Test</h2>
<div>
@Html.LabelFor(a => a.ParentName)
@Html.EditorFor(a => a.ParentName)
</div>
<div>
@Html.LabelFor(a => a.children)
@Html.EditorFor(a => a.children)
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.