获取当前控制器

Val*_*mas 124 asp.net-mvc-3

我有一个View - _Edit住在里面News M/V/C.

我重用了V/M通过CategoryControlleras:

return PartialView("/Views/News/_Edit.cshtml", model);
Run Code Online (Sandbox Code Playgroud)

如何从内部View - _Edit提醒控制器名称?

当我:

alert('@ViewContext. RouteData.Values["controller"].ToString()');
Run Code Online (Sandbox Code Playgroud)

值为:News 但是,URL为:/Category/foobar

有没有办法让价值'Category'提醒?谢谢

Nic*_*zer 190

我把它放在我的部分观点中:

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()
Run Code Online (Sandbox Code Playgroud)

在您描述的相同情况下,它显示URL中描述的控制器(您的类别,产品对我而言),而不是部分视图的实际位置.

所以请改用此警报:

alert('@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()');
Run Code Online (Sandbox Code Playgroud)

  • Palpie下面的答案是一个(更容易记住)的快捷方式:`@ ViewContext.RouteData.Values ["controller"]` (25认同)
  • 只是一个fyi,你不需要得到`HttpContext.Current`.`Request`可直接使用. (6认同)
  • 顺便说一句,`["action"]`如果你想要动作方法的名字,那就有效. (3认同)

Pet*_*erg 116

我是这样做的,但也许它只是ASP.NET MVC 4

@ViewContext.RouteData.Values["controller"]
Run Code Online (Sandbox Code Playgroud)

  • 请记住,您的解决方案将返回当前正在执行的控制器.因此,如果浏览器向ControllerA发出请求,并且ControllerA从ControllerB呈现部分视图,则您的解决方案将返回ControllerB的名称,而Nicholas Sizer解决方案将返回ControllerA的名称. (12认同)

Sel*_*Sel 21

为所有控制器创建基类并在此处放置name属性:

public abstract class MyBaseController : Controller
{
    public abstract string Name { get; }
}
Run Code Online (Sandbox Code Playgroud)

在视野中

@{
    var controller = ViewContext.Controller as MyBaseController;
    if (controller != null)
    {
       @controller.Name
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器示例

 public class SampleController: MyBaseController 
    { 
      public override string Name { get { return "Sample"; } 
    }
Run Code Online (Sandbox Code Playgroud)

  • 清洁比其他方法IMO. (3认同)

小智 13

在View中获取当前Controller名称的其他方法

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
Run Code Online (Sandbox Code Playgroud)


小智 5

只需使用:

ViewContext.Controller.GetType().Name
Run Code Online (Sandbox Code Playgroud)

这将为您提供整个控制器的名称