Contributors:

Nick Harrison
Chris Massey

Using Templated View Helpers

Display and editor templated view helpers in ASP.NET MVC [Blog]

Alessandro Zifiglio offers an excellent introduction to the template helpers. He steps you through their importance, how they are used and how to create your own. He also touches on various ways attributes come into play to customize the final look.

He introduces the often overlooked DisplayName attribute as well as the HiddenInput attribute. For newer projects, you may want to use the Display attribute instead of DisplayName. The main attribute that I wish he had included would have been the UIHintAttribute, but we will get to that shortly. For now, know that this attribute can easily specify the name for the template that you might want to use.

Using Templates to Display Boolean Values as Yes/No Options [Blog]

Scott Mitchell provides a simple introduction to using to using UIHints to provide a nice alternative to the standard approach for displaying and editing Boolean values. He also introduces an additional attribute handy to have in your bag of tricks. The DataTypeAttribute allows you to specify how a string is being used. The full list of DataTypes provides very granular control especially for browsers with strong HTML5 support.

Using UIHint With ControlParameters in MVC [Blog]

Mike van der Meulen takes you on a deep dive into the intricacies of using UIHints  as he creates a custom ModelMetadataProvider to access extended properties of the UIHintAttribute. This deals with some rather advanced concepts so pace yourself and work up to this material

Styling Generated HTML

Styling markup generated by template view helpers is really no different from styling markup that you create by hand.In many ways it is probably even easier because it will be more consistent.

One trick that you often have to do though is explicitly adding a class attribute to the generated markup.  Doing this is not always intuitive the first time, but it does make sense after that.  The problem is that class means something very special in C# so you can’t just say new {class = “className”}, but you can say this:

@Html.TextBoxFor(x => x.Property, new {@class = "className" })

Beyond that, it is best practice not to specify style settings directly on tags
You may also want to specify the class on a containing element, for example

<span class="fieldEditor">
      @Html.EditorFor(m => m.Name)
</span>

And then in your css, you may have something like this:

.fieldEditor {
      /* Style settings for the container*/
}
.fieldEditor label {
      /* style settings for the label */
}
.fieldEditor input {
      /* style settings for the input control */
}

Here are a few more excellent resources worth taking a look at:

Foundation [Zurb]

Foundation by Zurb provides several templates using their grid css framework to allow you to quickly build a nice looking responsive UI

Bootstrap [Github]

Bootstrap is an alternate grid css framework built by Twitter. Once again we get templates a nice css framework to quickly build a nice looking responsive UI.

MVC Contrib Gallery [CodePlex]

MVC contrib gallery is a collection of several dozen templates ready to be dropped into any markup up generated from the standard MVC template.

Using Model Metadata

Model Metadata is a vast topic in MVC.   As we have already seen, metadata is used to control various aspects of how the views will be rendered.   We have seen the  DisplayNameAttribute, the HiddenInputAttribute, the DataTypeAttribute, and the UIHintAttribute.   We will see later how they can come into play with Validation.

Applying Attributes [MSDN Library]

It is probably already obvious, but we apply metadata through attributes.   In this of our models these will generally be applied to properties.

Working with Complex Types

Simplifying working with complex types is the motivation behind View Models. Despite the funny name, they serve several vital roles for security, performance, and maintainability.  The idea is to have an object housing all of the data needed for a View.   Sometimes this means combining properties from multiple objects.   Sometimes this means hiding or suppressing properties from the main object.   Sometimes this means eliminating cyclic references that would confuse any serializer.
If you are already familiar with Data Transfer Objects and the slight variants Composite Data Transfer Objects, you are already at least partially familiar with View Models.  

Part of the beauty of ViewModels is that there is a limit to how complex they need to be.   Since they are customized for a specific View, they only need to handle the complexities of that one View.

View Model Design And Use In Razor Views [Blog]

Mike Brind provides an excellent introduction to the concept of View Models.   He explains the motivation behind their development, the roles they can play in security and performance.  He also talks a bit about where the Annotation attributes belong, on the Business Entity or the View Model.   This is a hotly debated topic in some circles; just know that whichever route you take, someone is likely to disagree with you.

He also introduces a critical attribute if you want to add your annotation attributes to a level that is generated.   The MetadataType attribute allows you to associate the generated class with a class you code by hand where all of your attributes will be associated.

Finally he introduces the essential library AutoMapper.  If you ever find yourself having to map properties from one object to another, AutoMapper will be your friend.

Creating Custom Templates

The out of the box templates that you get with MVC are nice.   The seamlessly integrate with your application and you probably have no idea that you are even using a custom template.   When we can build on this and create some rich controls. With the proper templates in place, we can have a rich interactive application without having to do anything extra to tie it all together.

ASP .NET MVC datetime editor template using jQuery datepicker [Blog]

In this blog, Nick Harris steps you through from start to finish how to create a custom template that will make any nullable date field use a jQuery DatePicker.

This really is a must do in your web applications.   Follow these step by step instructions and never worry again about how your date fields are displayed.

Working with Enums and Templates In ASP.NET MVC [Blog]

Scott Allen works similar magic to define a template that will convert any enum into a drop down to select from the list of valid options.

He steps through creating a custom model metadata provider to get the framework to use a common template for all properties derived from enum.   The default behavior would treat enums as strings.  Out of the box, you can easily create a template for a specific enum such as MovieGenre in his example, but to have a single template work for all enums, the extra work is involved.

This is a little advanced and he does caution us that this approach has not been vetted for performance, but this is an intriguing approach.   Even if this is not performant  for a high volume site, this may make a great option for rapid prototyping.

Replacing the Built in Templates

Custom Display and Editor Templates with ASP.NET MVC 3 Razor [Blog]

Here Gerke M. Preussner steps through uncovering the details behind how the default built in templates are implemented.   They are not implemented using a view engine like the custom templates you and I might right.   They are compiled in code inside the System.Web.MVc assembly.   Gerke discovered a copy of the source code on CodePlex to help with his detective work, but if you have a copy of Reflector, your detective work will be a little easier:

ASP.NET MVC 3 Razor and .NET Reflector

Creating a Custom Model Metadata Provider

Diving into ASP.NET MVC3 Model Metadata Providors [DotNetCurry]

Raj Aththanayake starts out by providing an excellent explanation of the differences between the DisplayAttribute and DisplayNameAttribute. He then steps through creating attribute to support localization. Once you start relying on your own custom attributes, you will need your own metadata provider that will know to look for your new attribute and what to do with it.

He then steps through creating MyModelMetadataProvider derived from the built in DataAnnotationsModelMetaDataProvider and registering it so that it will be the provider used.This provides a nice foundation for creating your own provider as well as creating your own attributes.

Working with Enums and Templates In ASP.NET MVC [Blog]

We saw this blog post a little earlier, but it bears revisiting. When we looked at this earlier, we were primarily interested in how he created a custom editor template for an enumeration or Enums in general.

Now we can better understand how he worked his magic in the custom provider. He lets the standard DataAnnotationsModelMetaDataProvider do all of the work and simply extends the GetMetadataForProperty method by calling the standard model provider. He uses a “_inner” field. I think that it is clearer to use a base class. My implementation would look similar to this:

public class CustomModelMetadataProvider
      
: DataAnnotationsModelMetadataProvider
  {
        
public override ModelMetadata GetMetadataForProperty
        
(Func<object> modelAccessor,
        
Type containerType, string propertyName)
    
{
          var result
= base.GetMetadataForProperty
          
(modelAccessor, containerType, propertyName);
          
if (result.TemplateHint == null &amp;&amp; typeof(enum)
          
.IsAssignableFrom(result.ModelType))
      
{
            result.TemplateHint
= "Enum";
      
}
          
return result;
    
}
  }
 

Let us know what you think!