繁体   English   中英

IEnumerable的ASP.NET MVC EditorTemplate

[英]ASP.NET MVC EditorTemplate for IEnumerable

我有一个具有2个属性的模型: stringIEnumerable<SomeModel> 如果我通过UiHintstring指定editortemplate, UiHint其应用。 但是,当我为IEnumerable<SomeModel>属性指定它时,什么也没发生。 我对IEnumerable有什么特别的需要吗?

如果我正确理解了您的问题,则需要用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)
  ...
}
...

适用于MVC 4。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM