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

RachMau_ 22 minutes ago
RachMau_

Blog Post: Top Support Solutions for Windows Azure Web Sites http://t.co/aEhzMOwOKR

prestonpeine 27 minutes ago
prestonpeine

RT @KristianNese: OK everyone! We got new UR3 for SC 2012 R2 and Windows Azure Pack. Some NVGRE stuff are solved in this rollup! #WAPack #NVGRE#SCVMM

sauminpatel 59 minutes ago
sauminpatel

8 ways to improve http://t.co/2avhFhGhnb Web API performance #webapi #aspnet #performance http://t.co/IuE5h8Pgw5

TechMike2kX One hour ago
TechMike2kX

RT @mscurah: #Windows #Azure Pack for #Hosting Service Providers http://t.co/Vridc3IXA5 via Byron Ricks

nasunotw One hour ago
nasunotw

RT @mscurah: #Windows #Azure Pack for #Hosting Service Providers http://t.co/Vridc3IXA5 via Byron Ricks