Last Updated: February 25, 2016
·
5.708K
· andrepiper

Get route attributes in MVC 5

I needed to apply class names to specific divs based on selected controller, action or id.

public class RouteAttributes
{
    public static string GetRouteParam(System.Web.Routing.RouteValueDictionary context,string section)
    {
        var routeContext = context;
        var sectionContext = section.ToLower();

        if (sectionContext.Contains("id") && routeContext.ContainsKey(sectionContext))
        {
            return routeContext[sectionContext].ToString();
        }
        else if (sectionContext.Contains("id") && HttpContext.Current.Request.QueryString.AllKeys.Contains(sectionContext))
        {
            return HttpContext.Current.Request.QueryString[sectionContext].ToString();
        }


        if (sectionContext.Contains("action") && routeContext.ContainsKey(sectionContext))
        {
            return routeContext[sectionContext].ToString();
        }
        else if (sectionContext.Contains("action") && HttpContext.Current.Request.QueryString.AllKeys.Contains(sectionContext))
        {
            return HttpContext.Current.Request.QueryString[sectionContext].ToString();
        }


        if (sectionContext.Contains("controller") && routeContext.ContainsKey(sectionContext))
        {
            return routeContext[sectionContext].ToString();
        }
        else if (sectionContext.Contains("controller") && HttpContext.Current.Request.QueryString.AllKeys.Contains(sectionContext))
        {
            return HttpContext.Current.Request.QueryString[sectionContext].ToString();
        }

        return string.Empty;
    }
}

** USAGE **

 @{
    //Global Variables

    var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

    var controller = RouteAttributes.GetRouteParam(routeValues, "controller");

    var action = RouteAttributes.GetRouteParam(routeValues, "action");

    var id = RouteAttributes.GetRouteParam(routeValues, "id");
}