IEnumerable的ASP.NET MVC EditorTemplate [英] ASP.NET MVC EditorTemplate for IEnumerable

查看:53
本文介绍了IEnumerable的ASP.NET MVC EditorTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

如果您的模型看起来像

 公共类TestModel{公共字符串ParentName {get;放;}[UIHint("HintTemplate")]公共IEnumerable< TestChildModel>孩子们{放;}} 

ChildModel

 公共类TestChildModel{public int id {get;放;}公共字符串ChildName {get;放;}} 

您的HintTemplate.cshtml应该看起来像

  @model IEnumerable< MVC3.Models.TestChildModel>@ {布局= null;}<!DOCTYPE html>< html>< head>< title> HintTemplate</title></head><身体>@foreach(模型中的var a){< div style ="background-color:#4cff00">@ Html.DisplayFor(m => a.ChildName)@ Html.EditorFor(m => a.ChildName)</div>}</body></html> 

您的视图

 <代码> @model MVC3.Models.TestModel@ {ViewBag.Title =测试";}< h2>测试</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> 

I have a model with 2 properties: string and IEnumerable<SomeModel>. If I specify editortemplate by UiHint for string, it is applied. But when I specify it for IEnumerable<SomeModel> property, nothing happens. Is there anything special that I need to do for IEnumerable?

Your HintTemplate model should be IEnumerable<SomeModel> (you will be iterating the model in the editor template). 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). 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

@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>

这篇关于IEnumerable的ASP.NET MVC EditorTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆