MVC DisplayFor Template Selection

627 views Asked by At

Am I right in saying that in MVC if I have a model entity, lets say Customer, and I use

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

it will look for a display template that is "Named" Customer to display the entity?

And, does MVC automatically perform iteration if the object you're passing the template is an IEnumerable or collection of some sort? E.g.

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

So if I wanted to create an additional view for Customer and force the helper to use it, say for example

@Html.DisplayFor(x => x.AllCustomers, "MyCustomTemplate")

then that template would have to be a strongly typed view of type IEnumerable correct? And I would have to create the iteration code myself?

Seems like MVC does the iteration bit if it recognizes that the model entity matches the view's model type.

1

There are 1 answers

0
Zabavsky On BEST ANSWER

it will look for a display template that is "Named" Customer to display the entity?

Yes. And it will use default display template for object if it doesn't find any.

And, does MVC automatically perform iteration if the object you're passing the template is an IEnumerable or collection of some sort?

The framework uses built in template for IEnumerable<T> where it performs the iterations, so technically yes.

then that template would have to be a strongly typed view of type IEnumerable correct?

Correct.

And I would have to create the iteration code myself?

You are right. Once you specify a custom display template name, the framework will use your template instead of default one, so it has to be a type of IEnumerable<T>.