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

preetham_reddyc 13 minutes ago
preetham_reddyc

RT @shanselman: Fantastic writeup on how @Azure WebJobs work http://t.co/V1qx3BqviZ

azurewindows 19 minutes ago
azurewindows

Adding a Co-administrator via the powershell http://t.co/VFXnXP1Igu #cloud #Azure #fb

FutureIsCloudy 32 minutes ago
FutureIsCloudy

Announcing the GA of Windows Azure Hyper-V Recovery Manager - In the Cloud - Site Home - TechNet Blogs http://t.co/f7OT9aKqhe

arnaudcleret 32 minutes ago
arnaudcleret

The Windows Azure Daily is out! http://t.co/ENqbjz8ezs Stories via @apri_anurapri @DaveRuijter

kamilazmer 44 minutes ago
kamilazmer

RT @StanZhelyazkov: Tips for Applying Update Rollup 2 on System Center 2012 R2 and Windows Azure Pack http://t.co/DS0rXl2jn5 #SysCtr #WAPack#SCOM#SCSM#SCVMM