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

francorobles 24 minutes ago
francorobles

RT @aspnet: Profile and debug your http://t.co/FLpiEg2zzX MVC app with Glimpse http://t.co/Bq5XoHAla7

hoshimi_212 26 minutes ago
hoshimi_212

RT @yasuyo_405: My code Works fine on localhost but not on remote server .[http://t.co/yfJuDM5588 mvc] http://t.co/Q0KHQVe9FP

Work_in_London 46 minutes ago
Work_in_London

#NET Developer, ASP. Net mvc, c#, agile - london en #London. Info: http://t.co/MJrmYxotM3

paperdhc 48 minutes ago
paperdhc

Profile and debug your http://t.co/YuAflXvxem MVC app with Glimpse http://t.co/uGwC6wohhO

sakiko_888 52 minutes ago
sakiko_888

RT @yasuyo_405: File Upload using MultipartFormDataStreamProvider to attached subdirecto http://t.co/fwtLqYW71V