ASP.NET MVC 3 - Partial vs Display Template vs Editor Template
Asked Answered
P

5

309

So, the title should speak for itself.

To create re-usable components in ASP.NET MVC, we have 3 options (could be others i haven't mentioned):

Partial View:

@Html.Partial(Model.Foo, "SomePartial")

Custom Editor Template:

@Html.EditorFor(model => model.Foo)

Custom Display Template:

@Html.DisplayFor(model => model.Foo)

In terms of the actual View/HTML, all three implementations are identical:

@model WebApplications.Models.FooObject

<!-- Bunch of HTML -->

So, my question is - when/how do you decide which one of the three to use?

What i'm really looking for is a list of questions to ask yourself before creating one, for which the answers can be used to decide on which template to use.

Here's the 2 things i have found better with EditorFor/DisplayFor:

  1. They respect model hierarchies when rendering HTML helpers (e.g if you have a "Bar" object on your "Foo" model, the HTML elements for "Bar" will be rendered with "Foo.Bar.ElementName", whilst a partial will have "ElementName").

  2. More robust, e.g if you had a List<T> of something in your ViewModel, you could use @Html.DisplayFor(model => model.CollectionOfFoo), and MVC is smart enough to see it's a collection and render out the single display for each item (as opposed to a Partial, which would require an explicit for loop).

I've also heard DisplayFor renders a "read-only" template, but i don't understand that - couldn't i throw a form on there?

Can someone tell me some other reasons? Is there a list/article somewhere comparing the three?

Puppetry answered 18/2, 2011 at 4:22 Comment(1)
The concepts behind editor and display templates are clearly defined in the documentation for asp.net mvc 2. Templates are partials which adhere to a specific convention. The situations which make templates better or worse than old partials are almost strictly dependent on whether or not the convention is worth adherence in your application.Rothermere
U
308

EditorFor vs DisplayFor is simple. The semantics of the methods is to generate edit/insert and display/read only views (respectively). Use DisplayFor when displaying data (i.e. when you generate divs and spans that contain the model values). Use EditorFor when editing/inserting data (i.e. when you generate input tags inside a form).

The above methods are model-centric. This means that they will take the model metadata into account (for example you could annotate your model class with [UIHintAttribute] or [DisplayAttribute] and this would influence which template gets chosen to generate the UI for the model. They are also usually used for data models (i.e. models that represent rows in a database, etc)

On the other hand Partial is view-centric in that you are mostly concerned with choosing the correct partial view. The view doesn't necessarily need a model to function correctly. It can just have a common set of markup that gets reused throughout the site. Of course often times you want to affect the behavior of this partial in which case you might want to pass in an appropriate view model.

You did not ask about @Html.Action which also deserves a mention here. You could think of it as a more powerful version of Partial in that it executes a controller child action and then renders a view (which is usually a partial view). This is important because the child action can execute additional business logic that does not belong in a partial view. For example it could represent a shopping cart component. The reason to use it is to avoid performing the shopping cart-related work in every controller in your application.

Ultimately the choice depends on what is it that you are modelling in your application. Also remember that you can mix and match. For example you could have a partial view that calls the EditorFor helper. It really depends on what your application is and how to factor it to encourage maximum code reuse while avoiding repetition.

Unharness answered 18/2, 2011 at 4:30 Comment(5)
That's a great answer, exactly what i was looking for. In reality i was banking on the fact you'd come and answer this. :) Thanks marcin.Puppetry
How do you use annotations to specify a display template and an editor template for a single property?Haman
@Haman either use convention and name your templates after the model they relate to (/Views/DisplayTemplates/MyModel.cshtml) or explicitly force it w/ the UIHint annotation.Docket
Any advice for which to pick for creating a reusable "register user" wizard? I want to create these views(and controllers) in a separate assembly if possible. Aka, a way to redistribute amongst several teams these resuable mvc forms/controllers. (we've created a single way to handle user/storing (webapi services)...but each team is creating their own mvc pages :< Thanks.Ecosystem
Where do you store those templates? Do I need to store them in Shared/EditorTemplates or is it possible to store them directly in the current controller folder (when I need them only there)?Photometer
S
15

You certainly could customize DisplayFor to display an editable form. But the convention is for DisplayFor to be readonly and EditorFor to be for editing. Sticking with the convention will ensure that no matter what you pass into DisplayFor, it will do the same type of thing.

Scevo answered 18/2, 2011 at 4:31 Comment(2)
I don't think there is really any question / doubt as to when one should use display templates vs editor templates. The real question appears to be when should you use templates vs partials. Your answer completely misses this.Spell
@Joshua - i think there was some question to that: "I've also heard DisplayFor renders a "read-only" template, but i don't understand that - couldn't i throw a form on there?"Scevo
F
13

Just to give my 2c worth, our project is using a partial view with several jQuery tabs, and each tab rendering its fields with its own partial view. This worked fine until we added a feature whereby some of the tabs shared some common fields. Our first approach to this was to create another partial view with these common fields, but this got very clunky when using EditorFor and DropDownListFor to render fields and drop downs. In order to get the ids and names unique we had to render the fields with a prefix depending on the parent partial view that was rendering it:

    <div id="div-@(idPrefix)2" class="toHide-@(idPrefix)" style="display:none">
    <fieldset>
        <label for="@(idPrefix).Frequency">Frequency<span style="color: #660000;"> *</span></label>

        <input name="@(idPrefix).Frequency"
               id="@(idPrefix)_Frequency"
               style="width: 50%;"
               type="text"
               value="@(defaultTimePoint.Frequency)"
               data-bind="value: viewState.@(viewStatePrefix).RecurringTimepoints.Frequency"
               data-val="true"
               data-val-required="The Frequency field is required."
               data-val-number="The field Frequency must be a number."
               data-val-range-min="1"
               data-val-range-max="24"
               data-val-range="The field Frequency must be between 1 and 24."
               data-val-ignore="true"/>

        @Html.ValidationMessage(idPrefix + ".Frequency")

        ... etc

    </fieldset>
</div>

This got pretty ugly so we decided to use Editor Templates instead, which worked out much cleaner. We added a new View Model with the common fields, added a matching Editor Template, and rendered the fields using the Editor Template from different parent views. The Editor Template correctly renders the ids and names.

So in short, a compelling reason for us to use Editor Templates was the need to render some common fields in multiple tabs. Partial views aren't designed for this but Editor Templates handle the scenario perfectly.

Footpoundsecond answered 20/2, 2012 at 21:18 Comment(1)
I had a similar issue using tabs and ended up using Steve Sanderson's BeginCollectionItem which generates the unique control id's for you: blog.stevensanderson.com/2010/01/28/…Unspoken
M
2

Another difference that hasn't been mentioned so far is that a partialview doesn't add model prefixes while a template does Here is the issue

Moravia answered 14/6, 2017 at 12:22 Comment(0)
R
1

Use _partial view approach if:

  1. View Centric Logic
  2. What to keep all _partial view related HTML in this view only. In the template method, you will have to keep some HTML outside the Template View like "Main Header or any outer border/settings.
  3. Want to render partial view with logic (From controller) using URL.Action("action","controller").

Reasons to use Template:

  1. Want to remove ForEach(Iterator). Template is well enough to identify Model as a list type. It will do it automatically.
  2. Model Centric Logic. If multiple views are found in the same displayfor Template folder, then rendering will depend on Passed Model.
Ruthenium answered 5/10, 2015 at 7:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.