Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC 3 - Partial vs Display Template vs Editor Template
    primarykey
    data
    text
    <p>So, the title should speak for itself.</p> <p>To create re-usable components in ASP.NET MVC, we have 3 options (could be others i haven't mentioned):</p> <p><em>Partial View:</em></p> <pre><code>@Html.Partial(Model.Foo, "SomePartial") </code></pre> <p><em>Custom Editor Template:</em></p> <pre><code>@Html.EditorFor(model =&gt; model.Foo) </code></pre> <p><em>Custom Display Template:</em></p> <pre><code>@Html.DisplayFor(model =&gt; model.Foo) </code></pre> <p>In terms of the actual View/HTML, all three implementations are identical:</p> <pre><code>@model WebApplications.Models.FooObject &lt;!-- Bunch of HTML --&gt; </code></pre> <p><strong>So, my question is - when/how do you decide which one of the three to use?</strong></p> <p>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.</p> <p>Here's the 2 things i have found better with EditorFor/DisplayFor:</p> <ol> <li><p>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").</p></li> <li><p>More robust, e.g if you had a <code>List&lt;T&gt;</code> of something in your ViewModel, you could use <code>@Html.DisplayFor(model =&gt; model.CollectionOfFoo)</code>, 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).</p></li> </ol> <p>I've also heard DisplayFor renders a "read-only" template, but i don't understand that - couldn't i throw a form on there?</p> <p>Can someone tell me some other reasons? Is there a list/article somewhere comparing the three?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload