Arnis Lapsa
Arnis Lapsa

Reputation: 47597

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?

Upvotes: 7

Views: 2069

Answers (1)

Eilon
Eilon

Reputation: 25704

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

Upvotes: 16

Related Questions