如果我创建一个返回 ActionResult 的 Controller 方法,然后在最后调用 View() ,是否有任何方法可以让 Filter (或类似的东西)将返回的结果从 View() 发出的 ViewResult 更改为 PartialViewResult基于请求中的条件?
显然,我可以在 Controller 方法本身中包含返回 ViewResult 或 PartialViewResult 的代码,但这会出现在很多地方,因此看起来过滤器的使用很好。我尝试在 IResultFilter 的两种方法中执行此操作,但没有看到输出发生变化。
如果这是不可能的,那么我将考虑在我的基本 Controller 中创建一些名为 ViewOrPartial 之类的方法,我可以调用它们而不是 View,但我想在放弃 Filter (或类似的东西)之前寻求更广泛的智慧)方法。
谢谢, 马修
更新:看来我所尝试的内容和现在基于 Darin 代码的工作之间至少有一个区别是我重写了 OnResultExecuting (并且我也尝试过 OnResultExecuted),而 Darin 的代码重写了 OnActionExecuted。这看起来很奇怪还是我可能忽略了其他事情?我很高兴它能工作,但将它附加到 IResultFilter 接口(interface)似乎更有意义。我将不得不更多地研究这两个接口(interface)的意图。
最佳答案
是的,这是可能的:
public class MyActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var result = filterContext.Result;
var viewResult = result as ViewResult;
var someValue = filterContext.Controller.ValueProvider.GetValue("someValue");
if (viewResult != null && someValue != null && someValue.AttemptedValue == "foo")
{
// if the controller action returned a view result
// and the someValue parameter equals foo we replace the
// view result initially returned by the action by a
// partial view result
var partialResult = new PartialViewResult();
partialResult.ViewData.Model = viewResult.Model;
filterContext.Result = partialResult;
}
}
}
然后装饰:
[MyActionFilter]
public ActionResult Foo()
{
MyViewModel vm = ...
return View(vm);
}
关于asp.net-mvc-3 - MVC3 : Is it possible to change the result type outside of the code of the action itself?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7947490/