Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Html.Display for a custom object, not the whole Model?

I have the following view-model for my MVC3 Razor view:

 public class UserProfileModel
 {
     public Person[] Persons { get; set; }
     //some other fields
 }

I want to display all the persons in my Razor view like:

foreach (var person in Model.Persons)
{
<div>
    @* some custom formatting *@
    @Html.Display(person)
</div>
}

@Html.Display or @Html.DisplayFor seems to not work for me..

I can create a separate stongly-typed view using Person as a model and call @Html.DisplayForModel there, but is there a way to go without a separate view?

like image 786
Shaddix Avatar asked Oct 01 '11 13:10

Shaddix


1 Answers

Create a partial view file called Person.cshtml inside ~/Views/Shared/DisplayTemplates. Make it strongly typed to Person class.

Implement the structure of your view.

Then when you call it like below (on your case), you will get what you expected :

foreach (var person in Model.Persons)
{
<div>
    @* some custom formatting *@
    @Html.DisplayFor(m => person)
</div>
}
like image 59
tugberk Avatar answered Nov 09 '22 01:11

tugberk