【问题标题】:Return View from ActionFilter从 ActionFilter 返回视图
【发布时间】:2010-10-05 04:27:21
【问题描述】:

我有一个 ActionFilter 来检查 URL 中的参数是否有效。 如果它无效,我必须渲染一个视图。我不想重定向,因为我仍然需要 ActionExecutingContext。 可以吗?

    public override void  OnActionExecuting(ActionExecutingContext filterContext)
    {
        Guid processIdentifier = (Guid)filterContext.RouteData.Values["processIdentifier"];
        //if processIdentifier  not found render a view with message and some other objects in ViewData
        filterContext.Controller.ViewData.ModelState.AddModelError("WrongProcessIdentifier", "The process-id you supplied is not valid");
        base.OnActionExecuting(filterContext);
    }

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    HandleErrorAttribute 有我想要的东西。

    filterContext.Result = new ViewResult
                {
                    ViewName = "MessagePage",
                    ViewData = filterContext.Controller.ViewData,
                    TempData = filterContext.Controller.TempData
                };
    

    【讨论】:

    • 我认为您应该接受自己的答案,因为它包含代码
    • 无论如何,我故意不包含代码,因为这个代码区域现在随着 MVC 框架的每个版本而变化。我认为正确的答案是“做框架当前正在做的任何事情。”
    • 如果你需要设置模型,它是ViewData的一部分。 ViewData.Model.
    【解决方案2】:

    试试这个

    [HandleError]
    public ActionResult MyAction (int id)
    {
        // ...
    }
    

    并将你想要渲染的视图放入~/Views/Shared/Error.ascx

    【讨论】:

    • 像 [HandleError] 这样的过滤器仅适用于操作方法。 OnActionExecuting() 方法本身是一个过滤器而不是一个动作方法,所以像这样的属性没有效果。
    【解决方案3】:

    是的。查看 HandleErrorAttribute 的来源。

    【讨论】:

      猜你喜欢
      • 2013-06-23
      • 2017-02-13
      • 1970-01-01
      • 2020-06-07
      • 2017-06-28
      • 1970-01-01
      • 2023-03-28
      • 2016-01-08
      • 1970-01-01
      相关资源
      最近更新 更多