【问题标题】:ASP.NET MVC: How to access View Name in a Action FilterASP.NET MVC:如何在操作过滤器中访问视图名称
【发布时间】:2016-06-20 16:13:28
【问题描述】:

我在下面写了用于模型验证的动作过滤器-

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var viewData = filterContext.Controller.ViewData;
        var viewNme = filterContext.Controller;
        if (!viewData.ModelState.IsValid)
        {
            filterContext.Result = new ViewResult
            {
                ViewData = viewData,
                ViewName = "Test"

            };
        }
        base.OnActionExecuting(filterContext);
    }

如果我没有通过ViewName = "WhitePaper" 它会失败并显示以下消息 - “/Travelers.eBusiness.Travelers.Web”应用程序中的服务器错误。

未找到视图“索引”或其主视图,或者没有视图引擎支持搜索到的位置。搜索了以下位置:

我的问题是—— 我如何传递视图信息?

【问题讨论】:

标签: c# asp.net asp.net-mvc action-filter


【解决方案1】:

您可以在OnActionExecuted 事件上获取结果的视图名称。

这应该给你视图名称。

public override void OnActionExecuted(ActionExecutedContext filterContext)
{       
    var viewData = filterContext.Controller.ViewData;
    var view = filterContext.Result as ViewResultBase;
    if (view != null)
    {
        string viewName = view.ViewName;
        // If we did not explicitly specify the view name in View() method,
        // it will be same as the action name. So let's get that.
        if (String.IsNullOrEmpty(viewName))
        {
            viewName = filterContext.ActionDescriptor.ActionName;
        }
        // Do something with the viewName now

    }
}

filterContext.Controller.ViewData 将在操作方法执行后可用(不为空)。但是,如果您希望在 OnActionExecuting 事件中使用它,您可以考虑读取操作名称并使用它(假设您的操作方法正在返回一个视图而没有明确指定视图名称。)

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   var actionMethodName = filterContext.ActionDescriptor.ActionName;
   // This will be same as your view name if you are not explicitly
   // specifying a different view name in the `return View()` call

}

【讨论】:

  • 这并没有解决目的。这个过滤器用于模型验证。此处返回的视图名称是重定向页面的名称。
  • 我们在 return View() 调用中指定了不同的视图名称
  • 那么在方法执行之前你无法获取视图名称,因为你的操作方法可以根据某些条件返回任何视图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多