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.Key.ToLower()),
            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

<configuration>
 <system.web>
  <pages>
   <namespaces>
    <add namespace="Antix.Web.Mvc"/>
   </namespaces>
  </pages>
 </system.web>
<configuration>
		

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

StalderDotNet 37 minutes ago
StalderDotNet

Integrating Ajax and Partial Views in http://t.co/g8ZPALiLrO MVC http://t.co/jcyBaeuGWv

StalderDotNet 42 minutes ago
StalderDotNet

TDD for http://t.co/g8ZPALiLrO MVC Part 4: Unit Testing View Model Validation http://t.co/I3J1gBCHYb

StalderDotNet 42 minutes ago
StalderDotNet

TDD for http://t.co/g8ZPALiLrO MVC, Part 3: Contact Service Class http://t.co/2ETNqTcXjb

StalderDotNet 42 minutes ago
StalderDotNet

Oh, CRUD … It's Test-Driven Development for http://t.co/g8ZPALiLrO MVC, Part 2 http://t.co/Vxr26LD9bq

nateparm 43 minutes ago
nateparm

TDD for http://t.co/aF655uN87o MVC Part 4: Unit Testing View Model Validation http://t.co/YEhFyNxc82