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

topnewjob 45 minutes ago
topnewjob

UK Web Jobs: Senior .NET Developer – https://t.co/usukawIr7Q, MVC – Architecture Design 50K https://t.co/kwX2GYVj6j

londonitjob 45 minutes ago
londonitjob

UK Web Jobs: Senior .NET Developer – https://t.co/dEEy4m2tqO, MVC – Architecture Design 50K https://t.co/arQ0RKo6jq

leicester_job 1 hours ago
leicester_job

Jobs in Leicester: Senior .NET Developer – https://t.co/uJq5Qdj2jT, MVC – Architecture Design 50K https://t.co/hOL4CY2xMg

ukwebjobs 1 hours ago
ukwebjobs

Jobs in Leicester: Senior .NET Developer – https://t.co/zjlC5Np7fK, MVC – Architecture Design 50K https://t.co/6ltlMb9s1O

AdamSmitht1 1 hours ago
AdamSmitht1

#ASP.NET MVC 5 The model item passed into the dictionary is of type 'Leepio.Models.IndexViewModel', but this dicti… https://t.co/G2ylqTF3PR