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?
RouteData is a property of the base Controller class, so RouteData can be accessed in any controller. RouteData contains route information of a current request. You can get the controller, action or parameter information using RouteData as shown below.
As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application. The earlier style of routing, called convention-based routing, is still fully supported. In fact, you can combine both techniques in the same project.
In MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller. The RouteConfig. cs file is used to set routing for the application.
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"]);
}
}
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With