开发者

How an i make an ASP.NET MVC3 DisplayTemplate which displays the contents of a Collection?

I'm trying to display the contents of a collection, in my View .. but using a DisplayTemplate to handle the definition of the view, for that specialized property/object.

eg.

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

and the foo object is..

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

and...

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

So i created a folder called DisplayTemplates, in my View folder for this Controller. I then added in a file called Foo.cshtm开发者_C百科l with the following content

@model MyNamespace.....Foo

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

and what i have getting displayed on my view?

System.Collections.Generic.List`1[MyNamespace.....Foo]

. I've confirmed that there is at least one item in this collection. Any ideas, folks?


Found my answer :)

I (incorrectly had)

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

but I should NOT have been using DisplayTextFor but DisplayFor

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

Also, I have purchased copy of Steve Sanderson's Pro ASP.NET MVC2 Framework (2nd Edition).pdf and on page 423 he says (and I sincerly hope I'm not infringing on copyright, here).

For example, you could now render an enumerable collection of Person instances with a single line of view markup—for example:

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

And he was correct and this text highlighted my mistake.

Win :)


I think it should be :

@model MyNamespace.....Foo

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

You could even use the <text> tag.

See Scott Gu's Post for Details: ASP.NET MVC 3: Razor’s @: and syntax

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜