Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given htmlHelper + action name, how to figure out controller name?

How does HtmlHelper.ActionLink(htmlhelper,string linktext,string action) figures out correct route?

If i have this=>

HtmlHelper.ActionLink("Edit","Edit")

Mvc automatically finds out correct route.

i.e. - if controller was Product, it will render anchor with href product/edit.

So - how to figure out controller name when i got htmlHelper + action name combo?

like image 784
Arnis Lapsa Avatar asked Jan 02 '10 01:01

Arnis Lapsa


1 Answers

If your HtmlHelper looks something like:

public static string MyHelper(this HtmlHelper htmlHelper,
                             ... some more parameters ...) {

    return ... some stuff ...
}

Then from your helper, access:

RouteData routeData = htmlHelper.ViewContext.RouteData;
string controller = routeData.GetRequiredString("controller");

The RouteData object contains all the values that were processed by ASP.NET Routing for the current request. This will include the parameter names and values from the route, such as "{controller}/{action}/{id}". Many of the built-in ASP.NET MVC helpers grab "ambient" data from there so that the developer doesn't have to type them in for every helper they use.

You can also download the full source code to ASP.NET MVC from here:

  1. ASP.NET MVC 1.0 RTM source code
  2. ASP.NET MVC 2 Release Candidate source code
like image 131
Eilon Avatar answered Oct 24 '22 03:10

Eilon