Friday 14 October 2011

Customising MVC View Rendering EditorTemplates | Display Templates | UIHint

There are a myriad of ways to customise the HTML output of an MVC View.

A simple example is the rendering of a Model.DateTime property (eg Person.DateOfBirth) - such fields are often persisted within the Data Source (a SQL/Oracle database or XML file for example) as a DateTime type.

But sometimes you don't want the Time component to display on the UI, as is the the default behaviour when you have View markup (with Razor syntax) like this:

<div class="editor-label">
            @Html.LabelFor(model => model.DATE_REVISED)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DATE_REVISED, "_DateTime")
            @Html.ValidationMessageFor(model => model.DATE_REVISED)
        </div>

This post, under the heading 'Specifying Model Display Format' explains some of the various ways you can change this behaviour with MVC3.

One of the ways i was looking into was the use of the UIHint attribute.

What i didn't realise is that you can't just put a Partial View in the View/Shared folder, it needs to be in the Views/Shared/EditorTemplates for your 'Edit' views and in Views/Shared/DisplayTemplates for your 'Details' views.

You gota know the Convention man - it's all Convention over Configuration - thats the name of the ASP.Net MVC game (and MVC in general)!

The other Convention which is good to know:

If you name the View with the same name as the Type which comprises the View's Model

eg
@model System.DateTime
 
// More View markup which determines the how the Model will be rendered 

needs a View named 'dateTime', 'DateTime' or '_DateTime' (appears Convention is that the View name does not have to match the case formatting of the type name and it can have an underscore at the beginning - any exceptions to this and .Net will not match the Partial View to the type).

and then .Net will pick it up automatically, even without the [UIHint] annotation on the Model Property.

This is good news if you're Models are being generated automatically via Entity Framework!

NOTE: Having a Partial View over-ride the rendering of type System.DateTime will make EVERY DateTime property, application wide, render using the mark-up contained in that Partial View! 

[ie if you have to add heaps of Annotations, and then need to re-generate, all your customising will be over-ridden!]

No comments:

Post a Comment