EditorTemplates and MVC2

by Kenny Eliasson 19. April 2010 15:10

Been upgrading our MVC-project at work to MVC2. A pleasant journey without much hassle. After upgrading I of course wanted to play around with the EditorTemplates.

I easily implemented my own EditorTemplates for Strings, Int32's, MultilineText, Bools and other "simple" types. I then realized that it would be sweet if all properties ending with "Color" would use my Color-template that included some Javascript for a color-picker. I remembered that i saw something like that in Tekpubs MVC-movies. What I needed to do was to create my own ModelMetadataProvider. Luckily enough yu can just inherit from the default DataAnnotationsModelMetadataProvider and override CreateMetaData().

My ModelMetadataProvider looked like this after my small tweak.

public class CustomMetaDataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(System.Collections.Generic.IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            var metaData = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
            if(propertyName != null) {
                if (propertyName.EndsWith("Color")) {
                    metaData.TemplateHint = "Color";
                }   
            }
            return metaData;
        }
    }

After that we tell our MVC-app to use our Provider in Global.asax with 1 line.

ModelMetadataProviders.Current = new CustomlMetaDataProvider();

And as easy as that I've implemented my own convention! :)

Tags: , ,
Categories: C# | MVC2 | Templates

Comments

bertilsson
bertilsson Sweden on 4/21/2010 3:32:10 PM

Would be nice with something like Fluent Nhibernates way of adding conventions to automapping in a ModelMetadataProvider Smile But maybe I should build one insted of complaining about it ;)

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading