2009-02-03 55 views
13

我有一個ActionFilter,用於檢查URL中的參數是否有效。 如果它無效,我必須渲染一個視圖。我不想重定向,因爲我仍然需要ActionExecutingContext。 可以在做什麼?從ActionFilter返回視圖

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); 
    } 

回答

31

HandleErrorAttribute有我正在尋找。

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

是的。查看HandleErrorAttribute的源代碼。

0

試試這個

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

並提出要渲染到~/Views/Shared/Error.ascx視圖。

+0

像[HandleError]這樣的過濾器只適用於動作方法。 OnActionExecuting()方法本身就是一個過濾器而不是一個操作方法,所以像這樣的屬性沒有任何作用。 – Levi 2009-02-05 03:56:33

+0

對不起,我甚至沒有看這個方法。我已更新。 – 2009-02-05 13:43:50