Sometimes its useful to be able target html elements on a particular page or you want to have specific styling according to a particular area, controller or action.

Here is a small extension to use route data to do just that.

namespace Antix.Web.Mvc {

 public static class Extentions {

  /// <summary>
  /// <para>Get a string from the route data</para>
  /// </summary>
  public static string RouteString(
      this ViewContext context, string template) {

   foreach (var value in context.RouteData.Values) {

    template = template.Replace(string.Format("{{{0}}}", 
            value.Value == null
                ? string.Empty
                : value.Value.ToString().ToLower());

   return template;

Making sure that the extension is in scope;
by importing on your page

<%@ Import Namespace="Antix.Web.Mvc"%>

or adding to you web.config

    <add namespace="Antix.Web.Mvc"/>

Call the function to retrieve the route data in a particular format like so...

<body class="<%= ViewContext.RouteString("{controller}_{action}") %>">

I've used this in the master page of my site to identify a page Body tag by controller and action.

<blog class="home_blogentry">
comments powered by Disqus

On Twitter Follow MrAntix on Twitter

rodrigoorzari 51 minutes ago

RT @SQLInsane: Getting started with Windows Azure HDInsight Service (Channel 9) via @ch9

rahulsahay19 One hour ago

[Blog] Hands-On with MVC - 10 days to launch -

Lewuathe One hour ago

One reason I want to try windows azure / Azure Search as a Service

rahulsahay19 One hour ago

Hands-On with MVC - 10 days to launch

eB2B_Cloud One hour ago

Demystifying Private Clouds - VMWare vCloud vs. Windows Azure vs. OpenStack vs. CloudStack #cloud