0

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.cshtml 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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647

2 Answers2

1

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 :)

Community
  • 1
  • 1
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
0

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

gideon
  • 19,329
  • 11
  • 72
  • 113
  • so you're suggesting that my custom DisplayTemplate is for ONE class instance ... so the fact that i'm trying to display a collection of Foo's isn't a problem .. the framework is smart enough to pick up that it should display my custom DisplayTemplate for each instance in the collection? – Pure.Krome Mar 14 '11 at 05:28
  • @Pure.Krome sorry misread your Q .. one option I can think of is having a **view** with a model `@IEnum` and within that view you'll call the **view** with a model `Foo` – gideon Mar 14 '11 at 07:58