Ben Finkel
Ben Finkel

Reputation: 4803

Simplest way to access RouteData.Values from View

I am using the following code to get the current "action" in my view because I want to custom build an actionlink based on it.

ViewContext.RequestContext.RouteData.Values("action")

My end goal is to build some action links with Javascript, and the .js needs to know what the current controller and action is since I'd like it to be flexible. I found the above by browsing through the framework but I don't know if I've found the correct thing.

i.e.

var routeData = ViewContext.RequestContext.RouteData;
var linkStub = '/@routeData.Values("controller")/@routeData.Values("action")';

Does anyone know if this is the easiest/most straightforward way to do this?

Upvotes: 20

Views: 60555

Answers (2)

Necros
Necros

Reputation: 3034

You get route data from RequestContext, and it doesn't really matter how you get to that (there are multiple ways). I wouldn't worry about going through multiple objects (probably only takes a few microseconds). You can make the code nicer tho, either by creating an extension method (of url helper for example) or making the control in question inherit custom implementation of WebViewPage where you create a shortcut for what you need. Like that:

public abstract class MyWebViewPage<TModel> : WebViewPage<TModel>
{
    public string ControllerName
    {
        get
        {
            return Url.RequestContext.RouteData.Values["controller"].ToString();
        }
    }

    public string ActionName
    {
        get
        {
            return Url.RequestContext.RouteData.Values["action"].ToString();
        }
    }
}

Upvotes: 13

maxlego
maxlego

Reputation: 4914

cleanest way would be an extension method

public static class MyUrlHelper
{
    public static string CurrentAction(this UrlHelper urlHelper)
    {
        var routeValueDictionary = urlHelper.RequestContext.RouteData.Values;
        // in case using virtual dirctory 
        var rootUrl = urlHelper.Content("~/");
        return string.Format("{0}{1}/{2}/", rootUrl, routeValueDictionary["controller"], routeValueDictionary["action"]);
    }
}

Upvotes: 29

Related Questions