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

javascriptd 32 minutes ago
javascriptd

RT @BubbleJobs: *JUNIOR JOB ALERT* Software Developer wanted at leading #eCommerce company in #Wythenshawe! http://t.co/JB1VqCKBD5 up to £3…

brianmains 44 minutes ago
brianmains

RT @PauloMorgado: > http://t.co/kfM3ZwUOpu MVC 6 formatters – XML and browser requests http://t.co/1NYVxET1qI

javascriptd 54 minutes ago
javascriptd

RT @aspnetweekly: Completing Project Tracking website using AngularJS and Web API - Part VII http://t.co/rol8zHkEVy #aspnet #angularjs #webapi

ColdwaterSoft 54 minutes ago
ColdwaterSoft

How to Configure SharePoint Server in Windows Azure http://t.co/720xKLLeYz via @CsharpCorner

taswarbhatti 55 minutes ago
taswarbhatti

Try Windows #Azure, Absolutely Free | http://t.co/sIVETazFOP pic.twitter.com/UIIP6Ud9ZD