July 12, 2012

Injecting Page Metadata in ASP.NET MVC

I’ve just pushed a new ASP.NET MVC Action Filter into Fabrik.Common for automatically injecting Page Metadata. This is a technique I’ve used on a number of CMS type projects recently, where the page title, description and keywords are generated using dynamic content.

Adding the filter

I recommend adding this one globally but you can always add directly to your Controller or Action in the normal fashion:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new InjectPageMetadataAttribute());
}

How it works

For pages that have dynamic metadata, inherit your View model from PageMetadata. You can then choose to override any of the properties below:

public class ListView : PageMetadata
{
    public override string MetaDescription
    {
        get { return "Products Description"; }
    }

    public override string MetaKeywords
    {
        get { return "Products, Stuff, Monies"; }
    }

    public override string PageTitle
    {
        get { return "Products"; }
    }
}

If you don’t override a property then the Action Filter will attempt to load fallback values from web.config’s appSettings:

<appSettings>
	<add key="MetaTitle" value="Default Title"/>
	<add key="MetaDescription" value="Default Meta Description"/>
	<add key="MetaKeywords" value="Default, Meta, Keywords"/>
</appSettings>

You can also just set these meta properties directly in your view pages, a common case for static views:

@model HomeView
@{
    ViewBag.Title = "Home Page";
    ViewBag.Description = "Home Page Description";
    ViewBag.Keywords = "Home Page Keywords";
}

The final thing to do is to add the necessary markup to your layout page <head>:

<head>
    <title>@ViewBag.Title - Fabrik.Common Example Project</title>
    <meta name="description" content="@ViewBag.MetaDescription" />
    <meta name="keywords" content="@ViewBag.MetaKeywords" />
</head>

Here I’m providing a title suffix containing the name of my site. You can use the format you like.

This really demonstrates just how powerful the dynamic ViewBag is. We can populate it in many different places (Views, Layouts, Controllers, Filters) in a number of ways.

You’ll find the full source on GitHub.

© 2022 Ben Foster