Getting controller name from razor

2019-01-20 06:57发布

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.

6条回答
We Are One
2楼-- · 2019-01-20 07:35
@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

MVC 3

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

MVC 4.5

@ViewContext.RouteData.Values["controller"].ToString();
查看更多
SAY GOODBYE
3楼-- · 2019-01-20 07:44

To remove need for ToString() call use

@ViewContext.RouteData.GetRequiredString("controller")
查看更多
倾城 Initia
4楼-- · 2019-01-20 07:46

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

ViewContext.Controller.GetType().Name
查看更多
We Are One
5楼-- · 2019-01-20 07:51
@{ 
    var controllerName = this.ViewContext.RouteData.Values["controller"].ToString();
}

OR

@{ 
    var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
}
查看更多
时光不老,我们不散
6楼-- · 2019-01-20 07:56

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.)

查看更多
小情绪 Triste *
7楼-- · 2019-01-20 08:01

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

查看更多
登录 后发表回答