Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 2 - When To Use Templates vs When to Use Partial Views

One of the new features in ASP.NET MVC 2 Preview 1 is support for the concept of Editor Templates and Display Templates which allow you to pre-define how a given object will be rendered for display or editing with a simple HTML helper call:

<%=Html.EditorFor(customer => customer) %>
<%=Html.DisplayFor(customer => customer) %>

This is pretty cool, but I don't really see the difference between this and a Partial View that serves the same purpose. Furthermore, in the examples I saw the Editor Templates do not contain the actual form tags and in the event that I need to provide some client-side functionality to a given editor (say through jQuery), I can't safely place that code in the template because I won't have a static handle on the form I am adding logic to in the client. In the application I am working on I have a mixture of Editor Templates and Partial Views which I render to edit content. Depending on the complexity of the form I am creating an editor for I've chosen one approach over the other, but this of course adds an undesirable level of inconsistency to the application.

Why use a Template over a Partial View or vise versa? Additionally, when using an Editor Template what is the ideal way to add client-side logic to the editor without copying it into every view that uses that editor?

like image 740
Nathan Taylor Avatar asked Aug 20 '09 19:08

Nathan Taylor


1 Answers

ScottGu explains some of this in his blogpost about MVC V2.

From what I gather this will create inputs for each of the properties of the object you pass to the helper. So if you have the object:

public class Customer
{
    public string Name { get; set; }
    [UIHint("MyCoolCalendar")]
    public DateTime CoolDate { get; set; }
}

And then create an editor:

<%= Html.EditorFor(customer => customer) %>

It will produce a text input for the name of the customer, and a MyCoolCalendar (which is a customdefined control) for CoolDate without you having to write a custom control to wrap the entire object. It automatically deduces the type of control from the type/uihint of the property. At least this is as I have understood it without having time to test it out yet.

like image 185
Runeborg Avatar answered Sep 30 '22 12:09

Runeborg