13

Normally we use DisplayForModel or EditorForModel to display and edit a single Customer object, respectively.

How to display a list of Customers using these templating scheme?

Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165

2 Answers2

20

Assuming you have a collection of customers in your view model

public class MyViewModel
{
    public IEnumerable<Customer> Customers { get; set; }
}

you could use the following in your view:

@Html.DisplayFor(x => x.Customers)

and then in the editor/display template (~/Views/Home/DisplayTemplates/Customer.cshtml or ~/Views/Shared/DisplayTemplates/Customer.cshtml):

@model AppName.Model.Customer
<div>@Model.Name</div>

The Customer partial will be then rendered for each element of the customers collection of your main model. The important thing is the naming convention: the partial should be situated in a DisplayTemplates subfolder and called the same as the collection type (Customer).

Jeroen
  • 60,696
  • 40
  • 206
  • 339
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Is there a way to specify a template name to something else? Customer Model is the same but if you would like to show it in different template? this doesnt work like DisplayFor(x=>x.Customers,"CustomerGridView") ? – akd Jul 15 '14 at 15:16
2

How about following Haack's tutorial ?

As great as this feature is, there is one template that’s conspicuously missing. ASP.NET MVC does not include a template for displaying a list of objects in a tabular format.

Earlier today, ScottGu forwarded an email from Daniel Manes (what?! no blog! ;) with a question on how to accomplish this. Daniel had much of it implemented, but was trying to get over the last hurdle. With Brad’s help, I was able to give him a boost over that hurdle. Let’s walk through the scenario.

nulltoken
  • 64,429
  • 20
  • 138
  • 130