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">
| < | February 2012 | |||||
|---|---|---|---|---|---|---|
| S | M | T | W | T | F | S |
| 29 | 30 | 31 | 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 1 | 2 | 3 |
Add-ins AJAX ASP.NET MVC Browsers C# Caching Compression CORS CSS CV Data Database DependencyResolver Development Entity Framework Error Handling File Upload Forms GDI+ HTML HTML Editor HTTP Interfaces JavaScript JQuery MCE MetadataProvider MSBuild Numbers Objects Patterns Progressive Enhancement Projects Publish Regex Resources Security SEO SMTP Source Control Strings Sub-Collections TDD Tools Twitter User Interface WCF Web Development WHS WMC XLinq XML
11 hours ago
verge
Microsoft teases Windows 8 'Consumer Preview' with Bing betta fish site http://t.co/lcJICazH