Getting controller name from razor

2019-01-20 07:43发布

问题:

I seem to be having a difficult getting something that should be easy. From within my view, using Razor, I'd like to get the name of the current controller. For example, if I'm here:

http://www.example.com/MyController/Index

How can I get the controller name, MyController from a Razor expression:

@* Obviously this next line doesn't work
    @Controller.Name
*@

I'm new to MVC, so if this is an obvious answer, don't attack me to bad.

回答1:

@{ 
    var controllerName = this.ViewContext.RouteData.Values["controller"].ToString();
}

OR

@{ 
    var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
}


回答2:

An addendum to Koti Panga's answer: the two examples he provided are not equivalent.

var controllerName = this.ViewContext.RouteData.Values["controller"].ToString();

This will return the name of the controller handling the view where this code is executed, whereas

var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

This will return the name of the controller requested in the URL.

While these will certainly be the same in most cases, there are some cases where you might be inside a partial view belonging to a different controller and want to get the name of the controller "higher-up" in the chain, in which case the second method is required.

(Apologies for posting this as a separate answer; I don't yet have the reputation to comment on his.)



回答3:

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

MVC 3

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

MVC 4.5

@ViewContext.RouteData.Values["controller"].ToString();


回答4:

To remove need for ToString() call use

@ViewContext.RouteData.GetRequiredString("controller")


回答5:

Also if you want to get the full controller's name (with "Controller" ending) you can use:

ViewContext.Controller.GetType().Name


回答6:

@ViewContext.RouteData.Values["controller"].ToString();