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

EleanorC20 17 minutes ago
EleanorC20

http://t.co/cP9NyyhGNw : Windows Azure Step by Step (Step by Step Developer) Windows Azure Step by Step (Step ... pic.twitter.com/gGMlrDszDB

OrigObjective 20 minutes ago
OrigObjective

Conventional HTML in http://t.co/xh675xsgtt MVC: Replacing form helpers http://t.co/R1ShOYOxhE

iccube 57 minutes ago
iccube

RT @mbcrump: Nice article on going responsive with #aspnet MVC by @samidip http://t.co/gaGW7VyJ6E #webdev

Epricity 58 minutes ago
Epricity

#Asp.NET Advanced Web Frameworks Gets Better with New Features, Bug Fixes ... - http://t.co/arKQ9ItMgc http://t.co/Rw7Msu1m9S

AndresSCM One hour ago
AndresSCM

Hands on lab day 2: Windows Azure Web Sites (@ ViveLab RTVC) https://t.co/CDiQ4S9wAn pic.twitter.com/EaQnX1S7DZ