我如何制作一个显示集合内容的ASP.NET MVC3 DisplayTemplate?

时间:2011-03-14 04:36:10

标签: c# .net asp.net-mvc asp.net-mvc-3 display-templates

我正在尝试在我的View中显示集合的内容..但是使用DisplayTemplate来处理该特定属性/对象的视图定义。

例如

<div class="display-label">Foos</div>
<div class="display-field">@Html.DisplayTextFor(_ => Model.Foos)</div>

和foo对象是..

public class Foo
{
    public string Name { get; set; }
    public string Blah { get; set; }
}

和...

public string MyModel
{
    public ICollection<Foo> Foos { get; set;}
}

所以我在这个Controller的View文件夹中创建了一个名为DisplayTemplates的文件夹。 然后我添加了一个名为Foo.cshtml的文件,其中包含以下内容

@model MyNamespace.....Foo

@Model [@Model.Blah] @Model.Name

以及我在观看中显示的内容?

  
    

System.Collections.Generic.List`1 [myNameSpace对象.....美孚]

  

。我已经确认此系列中至少有一个项目。 任何想法,伙计们?

2 个答案:

答案 0 :(得分:1)

找到我的答案:)

我(错误地拥有)

@Html.DisplayTextFor(_ => Model.Foos)

但我不应该使用DisplayTextForDisplayFor

@Html.DisplayFor(x => x.Model.Foos)

另外,我已经购买了Steve SandersonPro ASP.NET MVC2 Framework (2nd Edition)。pdf和第423页的副本,他说(我真的希望我没有侵犯版权,这里)。

  

例如,您现在可以渲染一个   可枚举的人物集合   具有单一视图的实例   标记 - 例如:

<%:Html.DisplayFor(x => x.MyPersonCollection) %>
//This would render the Person.ascx partial once 
//for each item in the collection. 

他是对的,这篇文章突出了我的错误。

赢:)

答案 1 :(得分:0)

我认为应该是:

@model MyNamespace.....Foo

[@:Model.Blah] @:Model.Name

您甚至可以使用<text>标记。

请参阅Scott Gu的帖子了解详情: ASP.NET MVC 3: Razor’s @: and syntax