0

我有一个具有 2 个属性的模型:stringIEnumerable<SomeModel>. UiHint如果我通过for指定 editortemplate string,则会应用它。但是当我为IEnumerable<SomeModel>属性指定它时,什么也没有发生。我需要为 IEnumerable 做些什么特别的事情吗?

4

2 回答 2

0

如果我正确理解您的问题,您需要将您的替换IEnumerableIList,然后使用以下方法:

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)
  ...
}
...

适用于 MVC 4。

于 2012-07-14T21:03:08.917 回答
0

您的 HintTemplate 模型应该是IEnumerable<SomeModel>(您将在编辑器模板中迭代模型)。或者,您可以在集合属性上使用 EditorFor,而不是 UIHint 注释(在这种情况下,EditorTemplate 模型将是 SomeModel;视图语法中不涉及迭代)。我在这篇文章中提供了类似的回复

如果您的模型看起来像

public class TestModel
{
    public string ParentName { get; set; }
    [UIHint("HintTemplate")]
    public IEnumerable<TestChildModel> children { get; set; }
}

童模

public class TestChildModel
{
    public int id { get; set; }
    public string ChildName { get; set; }
}

您的 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>

你的看法

@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>
于 2012-07-14T21:08:32.123 回答