C# – How to call Html.Display for a custom object, not the whole Model

asp.net-mvcasp.net-mvc-3crazor

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?

Best Answer

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