Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

There are a number of ways of implementing a pattern for using custom view model attributes, the following is similar to something my colleague Paul Haley and I developed at work which works pretty well.

The classes I’m going to create are really simple:

1. Abstract base attribute

2. Custom ModelMetadata provider which will derive from the DataAnnotationsModelMetadataProvider

Base Attribute

MetadataAttribute
  1. using System;
  2. using System.Web.Mvc;
  3. namespace Mvc2Templates.Attributes
  4. {
  5.     /// <summary>
  6.     /// Base class for custom MetadataAttributes.
  7.     /// </summary>
  8.     public abstract class MetadataAttribute : Attribute
  9.     {
  10.         /// <summary>
  11.         /// Method for processing custom attribute data.
  12.         /// </summary>
  13.         /// <param name="modelMetaData">A ModelMetaData instance.</param>
  14.         public abstract void Process(ModelMetadata modelMetaData);
  15.     }
  16. }

As you can see, the class simple has one method – Process.

Process accepts the ModelMetaData which will allow any derived custom attributes to set properties on the model meta data and add items to its AdditionalValues collection.

Custom Model Metadata Provider

For a quick explanation of the Model Metadata and how it fits in to the MVC 2 framework, it is basically a set of properties that are usually set via attributes placed above properties on a view model, for example the ReadOnly and HiddenInput attributes.

When EditorForModel, DisplayForModel or any of the other EditorFor/DisplayFor methods are called, the ModelMetadata information is used to determine how to display the properties.

All of the information available within the model metadata is also available through ViewData.ModelMetadata.

The following class derives from the DataAnnotationsModelMetadataProvider built into the mvc 2 framework.

I’ve overridden the CreateMetadata method in order to process any custom attributes that may have been placed above a property in a view model.

CustomModelMetadataProvider
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web.Mvc;
  5. using Mvc2Templates.Attributes;
  6. namespace Mvc2Templates.Providers
  7. {
  8.     public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
  9.     {
  10.         protected override ModelMetadata CreateMetadata(
  11.             IEnumerable<Attribute> attributes,
  12.             Type containerType,
  13.             Func<object> modelAccessor,
  14.             Type modelType,
  15.             string propertyName)
  16.         {
  17.             var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
  18.             attributes.OfType<MetadataAttribute>().ToList().ForEach(x => x.Process(modelMetadata));
  19.             return modelMetadata;
  20.         }
  21.     }
  22. }

 

As you can see, once the model metadata is created through the base method, a check for any attributes deriving from our new abstract base attribute MetadataAttribute is made, the Process method is then called on any existing custom attributes with the model meta data for the property passed in.

Hooking it up

The last thing you need to do to hook it up is set the new CustomModelMetadataProvider as the current ModelMetadataProvider, this is done within the Global.asax Application_Start method.

Global.asax
  1. protected void Application_Start()
  2.         {
  3.             AreaRegistration.RegisterAllAreas();
  4.             RegisterRoutes(RouteTable.Routes);
  5.             ModelMetadataProviders.Current = new CustomModelMetadataProvider();
  6.         }

In my next post, I’m going to demonstrate a cool custom attribute that turns a textbox into an ajax driven AutoComplete text box.

Hope this is useful.

Kind Regards,

Sean McAlinden.

Comments

# ASP.Net MVC 2 Auto Complete Textbox Custom View Model Attribute & EditorTemplate

Friday, June 11, 2010 7:03 PM by Sean McAlinden's Blog

In this post I’m going to show how to create a generic, ajax driven Auto Complete text box using the

# Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes - Sean McAlinden's Blog

Saturday, June 12, 2010 7:25 AM by DotNetShoutout

Thank you for submitting this cool story - Trackback from DotNetShoutout

# Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes - Sean McAlinden's Blog

Saturday, June 12, 2010 4:40 PM by iAwaaz-News-by-People

Thank you for submitting this cool story - Trackback from iAwaaz-News-by-People

# Twitter Trackbacks for Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes - Sean McAlinden's Blog [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes - Sean McAlinden's Blog         [asp.net]        on Topsy.com

# re: Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

Thursday, June 17, 2010 11:44 PM by Sam

The abstract base attribute is a great (although obvious) idea! For some reason I've been manually implementing all my new attributes inside the metadataprovider. Thanks.

# ASP.NET MVC 2 Auto Complete Textbox - Robbi, Tobbi und das Fliewat????t

Pingback from  ASP.NET MVC 2 Auto Complete Textbox - Robbi, Tobbi und das Fliewat????t

# re: Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

Thursday, October 21, 2010 4:37 AM by Stewart Celani

Gold =)

# re: Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

Wednesday, February 02, 2011 3:49 AM by Yoann

Wow, thanks a lot!

# Creating tooltips using data annotations in ASP.NET MVC

Sunday, April 17, 2011 7:21 PM by my great discovery

Creating tooltips using data annotations in ASP.NET MVC

# Generalizing Dropdown generation via Templating using Reflection in MVC &#8211; We are on .Net Blog

Pingback from  Generalizing Dropdown generation via Templating using Reflection in MVC &#8211; We are on .Net Blog

# re: Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

Friday, September 14, 2012 2:21 PM by Mccaskill

WOW just what I was looking for. Came here by searching for

ASP.NET

# re: Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

Sunday, September 16, 2012 2:11 AM by Gabbard

I quite like reading an article that can make people think.

Also, thanks for allowing me to comment!

# Creating tooltips using data annotations in ASP.NET MVC &laquo; Silverhair2010&#039;s Blog

Pingback from  Creating tooltips using data annotations in ASP.NET MVC &laquo; Silverhair2010&#039;s Blog

# re: Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

Saturday, October 20, 2012 6:28 PM by Bello

These are actually great ideas in regarding blogging. You have

touched some good points here. Any way keep up wrinting.

# re: Custom ASP.Net MVC 2 ModelMetadataProvider for using custom view model attributes

Thursday, January 17, 2013 8:40 PM by buy wow gold

Iˇll right away seize your rss feed as I can not find your e-mail subscription hyperlink or newsletter service. Do you've any? Kindly let me realize so that I may just subscribe. Thanks.

buy wow gold http://www.wow-gold-team.com

Leave a Comment

(required) 
(required) 
(optional)
(required)