簡體   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