我想在我的母版页中设置一个CSS类,这取决于当前控制器和动作。我可以通过ViewContext.Controller.GetType()访问当前控制器。名称,但我如何得到当前的行动(如索引,显示等)?


在MVC中,你应该为视图提供所有的数据,而不是让视图收集自己的数据,所以你能做的就是在你的控制器动作中设置CSS类。

ViewData["CssClass"] = "bold";

并从视图中的ViewData中选取这个值

使用ViewContext并查看RouteData集合以提取控制器和操作元素。但是我认为设置一些数据变量来指示应用程序上下文(例如,“editmode”或“error”)而不是控制器/动作减少了视图和控制器之间的耦合。

获取视图的当前Id:

ViewContext.RouteData.Values["id"].ToString()

获取当前控制器。

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

在RC中,你也可以提取路由数据,比如action方法名

ViewContext.Controller.ValueProvider["action"].RawValue
ViewContext.Controller.ValueProvider["controller"].RawValue
ViewContext.Controller.ValueProvider["id"].RawValue

针对MVC 3的更新

ViewContext.Controller.ValueProvider.GetValue("action").RawValue
ViewContext.Controller.ValueProvider.GetValue("controller").RawValue
ViewContext.Controller.ValueProvider.GetValue("id").RawValue

针对MVC 4的更新

ViewContext.Controller.RouteData.Values["action"]
ViewContext.Controller.RouteData.Values["controller"]
ViewContext.Controller.RouteData.Values["id"]

MVC 4.5更新

ViewContext.RouteData.Values["action"]
ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["id"]

我知道这是一个老问题,但我看到了它,我认为您可能对一个替代版本感兴趣,而不是让您的视图处理检索它需要的数据。

在我看来,一个更简单的方法是重写onactionexecution方法。你被传递一个ActionExecutingContext,它包含ActionDescriptor成员,你可以用它来获取你正在寻找的信息,也就是ActionName,你也可以到达ControllerDescriptor,它包含ControllerName。

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    ActionDescriptor actionDescriptor = filterContext.ActionDescriptor;
    string actionName = actionDescriptor.ActionName;
    string controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
    // Now that you have the values, set them somewhere and pass them down with your ViewModel
    // This will keep your view cleaner and the controller will take care of everything that the view needs to do it's job.
}

希望这能有所帮助。如果有什么不同的话,至少它会为其他问你问题的人提供一种选择。

我投票给这个2:

string currentActionName = ViewContext.RouteData.GetRequiredString("action");

and

string currentViewName = ((WebFormView)ViewContext.View).ViewPath;

您可以检索当前视图的物理名称和触发该视图的操作。它可以在partial *中使用。Acmx页来确定主机容器。

扩展Dale Ragan的回答,他的重用示例,创建一个派生于Controller的ApplicationController类,然后让所有其他控制器派生于这个ApplicationController类,而不是Controller。

例子:

public class MyCustomApplicationController : Controller {}

public class HomeController : MyCustomApplicationController {}

在你的新ApplicationController上创建一个名为ExecutingAction的属性,带有这个签名:

protected ActionDescriptor ExecutingAction { get; set; }

然后在onactionexecution方法中(来自Dale Ragan的回答),简单地将ActionDescriptor分配给这个属性,你可以在任何控制器中随时访问它。

string currentActionName = this.ExecutingAction.ActionName;

我看到了不同的答案,想出了一个类助手:

using System;
using System.Web.Mvc;

namespace MyMvcApp.Helpers {
    public class LocationHelper {
        public static bool IsCurrentControllerAndAction(string controllerName, string actionName, ViewContext viewContext) {
            bool result = false;
            string normalizedControllerName = controllerName.EndsWith("Controller") ? controllerName : String.Format("{0}Controller", controllerName);

            if(viewContext == null) return false;
            if(String.IsNullOrEmpty(actionName)) return false;

            if (viewContext.Controller.GetType().Name.Equals(normalizedControllerName, StringComparison.InvariantCultureIgnoreCase) &&
                viewContext.Controller.ValueProvider.GetValue("action").AttemptedValue.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) {
                result = true;
            }

            return result;
        }
    }
}

所以在视图(或master/layout)中,你可以这样使用它(Razor语法):

            <div id="menucontainer">

                <ul id="menu">
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home", "index", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("account","logon", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("Logon", "Logon", "Account")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home","about", ViewContext)) {
                            @:class="selected"
                        }>@Html.ActionLink("About", "About", "Home")</li>
                </ul>

            </div>

希望能有所帮助。

你可以从ViewContext的RouteData中获取这些数据

ViewContext.RouteData.Values["controller"]
ViewContext.RouteData.Values["action"]

我使用ASP。NET MVC 4,这是为我工作:

ControllerContext.Controller.ValueProvider.GetValue("controller").RawValue
ControllerContext.Controller.ValueProvider.GetValue("action").RawValue

在控制器中重写此函数

protected override void HandleUnknownAction(string actionName) 
{  TempData["actionName"] = actionName;
   View("urViewName").ExecuteResult(this.ControllerContext);
}