Click here to Skip to main content
13,259,779 members (46,625 online)
Click here to Skip to main content
Add your own
alternative version


23 bookmarked
Posted 31 Jul 2011

ASP.NET MVC: Add HTML5 Microdata to Your Applications using Metadata Providers

, 3 Apr 2012
Rate this:
Please Sign up or sign in to vote.
You can use Metadata Providers to add microdata to your ASP.NET MVC applications.

Microdata vocabularies provide the semantics, or meaning of an Item. You can use Metadata Providers to add microdata to your ASP.NET MVC applications.

Table of Contents

Lately, I’ve been reading lately some stuff about HTML5, and one of the things that I really liked was microdata. I’ve been Googling and I was surprised that I almost couldn’t find any information about how to use it in ASP.NET, that’s why I’ve decided to write this article.

HTML5 Microdata Overview

From Google:

The HTML5 microdata specification is a way to label content to describe a specific type of information—for example, reviews, person information, or events. Each information type describes a specific type of item, such as a person, and event, or a review. For example, an event has the properties venue, starting time, name, and category.

A common HTML code block:

<div>My name is Bob Smith but people call me Smithy. Here is my home page:
 <a href=""></a>
 I live in Albuquerque, NM and work as an engineer at ACME Corp.</div>

Using microdata:

<div itemscope itemtype="">
  My name is <span itemprop="name">Bob Smith</span>
  but people call me <span itemprop="nickname">Smithy</span>.
  Here is my home page:
  <a href="" itemprop="url"></a>
  I live in Albuquerque, NM and work as an <span itemprop="title">engineer</span>
  at <span itemprop="affiliation">ACME Corp</span>.

More information (see also the References section): HTML5 Microdata: Why isn’t anyone talking about it?

Creating a Microdata Metadata Provider

1. Create a Custom Attribute for Microdata

This attribute is used to “decorate” model properties with microdata. It can be used directly in the model properties, or it can be used in a MetadataType class, exactly the same way that DataAnnotations are used.

[AttributeUsage(AttributeTargets.Property | 
      AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class MicrodataAttribute : Attribute
    public bool ItemScope { get; set; }
    public string ItemType { get; set; }
    public string ItemId { get; set; }
    public string ItemProperty { get; set; }
    public string ItemReference { get; set; }

    public MicrodataAttribute()

    public MicrodataAttribute(string property)
        this.ItemProperty = property;

    public RouteValueDictionary GetAttributes()
        var attributes = new RouteValueDictionary();

            attributes.Add("itemscope", "itemscope");

            attributes.Add("itemtype", this.ItemType);

            attributes.Add("itemid", this.ItemId);

            attributes.Add("itemprop", this.ItemProperty);

            attributes.Add("itemref", this.ItemReference);

        return attributes;

2. Create a Custom Model Metadata Provider

I decided to create a custom Model Metadata Provider that inherits from DataAnnotationsModelMetadataProvider, because I wanted to use my provider in a similar way.

public class MicrodataModelMetadataProvider : DataAnnotationsModelMetadataProvider
    protected override ModelMetadata CreateMetadata(
        IEnumerable<Attribute> attributes,
        Type containerType,
        Func<object> modelAccessor,
        Type modelType,
        string propertyName)
        ModelMetadata metadata = base.CreateMetadata(

        // if no property name is specified, use fully qualified name of the Type
        string key = string.IsNullOrEmpty(propertyName) ?
            modelType.FullName :

        var microdata = attributes.OfType<MicrodataAttribute>().FirstOrDefault();

        if(microdata != null)
            metadata.AdditionalValues[key] = microdata.GetAttributes();

        return metadata;

3. Configuration

Initialize it in Global.asax:

protected void Application_Start()
    // code ommited for brevity
    // .....

    ModelMetadataProviders.Current = new MicrodataModelMetadataProvider();

4. HTML Helpers

public static class MicrodataExtensions
    // Strongly-typed helper:
    // Html.GetMicrodataFor(x => x.Name)
    public static RouteValueDictionary GetMicrodataFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
                 Expression<Func<TModel, TProperty>> expression)
        ModelMetadata metadata = 
           ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        string propertyName = GetMemberName(expression);

        return GetValuesFromMetadata(metadata, propertyName);

    // Non strongly-typed helper:
    // Html.GetMicrodataFor("Name")
    public static RouteValueDictionary GetMicrodata<TModel>(
        this HtmlHelper<TModel> htmlHelper, string propertyName)
        ModelMetadata metadata = 
          ModelMetadata.FromStringExpression(propertyName, htmlHelper.ViewData);

        return GetValuesFromMetadata(metadata, propertyName);

    // Gets microdata attributes for class type
    public static RouteValueDictionary GetMicrodataForType<TModel>(
        this HtmlHelper<TModel> htmlHelper)
        ModelMetadata metadata = 
          ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel));
        string propertyName = typeof(TModel).FullName;

        return GetValuesFromMetadata(metadata, propertyName);

    #region Private methods

    private static RouteValueDictionary GetValuesFromMetadata(
                   ModelMetadata metadata, string propertyName)
        if(metadata == null)
            return new RouteValueDictionary();

        RouteValueDictionary values = 
            metadata.AdditionalValues.Any(x => x.Key == propertyName) ?
            metadata.AdditionalValues[propertyName] as RouteValueDictionary :
            new RouteValueDictionary();

        return values;

    private static string GetMemberName<TModel, TProperty>(
            Expression<Func<TModel, TProperty>> expression)
        if(expression == null)
            return typeof(TModel).FullName;

        var memberExpression = expression.Body as MemberExpression;

        if(memberExpression == null)
            return string.Empty;

        return memberExpression.Member.Name;


Using the Code

Using the code is really easy. You just need to decorate your model class with Microdata attributes. Please note that you can use attributes for validation exactly the same way:

[Microdata(ItemScope = true, ItemType = "")]
public class Person
    public string Name { get; set; }

    public string Email { get; set; }

    public string PhoneNumber { get; set; }

    public DateTime BirthDate { get; set; }

As an alternative, create a Metadata class instead:

public class Person
    public string Name { get; set; }

    public string Email { get; set; }

    public string PhoneNumber { get; set; }

    public DateTime BirthDate { get; set; }

[Microdata(ItemScope = true, ItemType = "")]
public partial class PersonMetadata
    public string Name { get; set; }

    [Microdata("email", ItemReference="abc")]
    public string Email { get; set; }

    [Microdata("telephone", ItemId="123")]
    public string PhoneNumber { get; set; }

    public DateTime BirthDate { get; set; }

Finally, use the HTML helpers in your views to get microdata attributes:

And that’s it! This is the output:

Feel free to download the demo project.




This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Rui Jarimba
Software Developer (Senior)
Italy Italy
My name is Rui Jarimba and I was born in Madeira island, Portugal and I currently live in Rome, Italy.

I have more than 10 years of experience developing software using the .NET Framework and other technologies (Web development, Databases, ...).

Some of my professional interests are: software development best practices, software architecture, cloud computing, Continuous Integration (CI), Continuous Delivery (CD) and agile methodologies such as Scrum, Kanban, Lean and any other methodology that can help me to become a better and more productive software engineer.

I believe in good code - code that is readable, maintainable, reusable, testable and deployable. This means that I'm not the "quick and dirty" type, I write code for the medium/long term whenever possible.

Something else about me - I love music, I am an amateur photographer, not a big fan of gyms (I prefer to do some outdoor activity such as walking/hiking), big foodie (I love Mediterranean cuisine and my glass of wine!).

You may also be interested in...


Comments and Discussions

QuestionNuGet Pin
PhillipPDX22-Apr-14 13:27
memberPhillipPDX22-Apr-14 13:27 
AnswerRe: NuGet Pin
Rui Jarimba22-Apr-14 22:34
professionalRui Jarimba22-Apr-14 22:34 
QuestionSource code Pin
Rui Jarimba18-Feb-12 13:20
memberRui Jarimba18-Feb-12 13:20 
Hi all,

I'm trying to upload the source code to CodeProject, but so far no luck Frown | :(
GeneralMy vote of 5 Pin
ashved17-Feb-12 9:56
memberashved17-Feb-12 9:56 
GeneralRe: My vote of 5 Pin
Rui Jarimba18-Feb-12 13:04
memberRui Jarimba18-Feb-12 13:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 3 Apr 2012
Article Copyright 2011 by Rui Jarimba
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid