MVC3:是否可以在操作本身的代码之外更改结果类型?
如果我创建一个返回 ActionResult 的控制器方法,然后在最后调用 View() ,有没有办法让 Filter (或类似的东西)根据条件将返回的结果从 View() 发出的 ViewResult 更改为 PartialViewResult在请求中?
显然,我可以在控制器方法本身中包含返回 ViewResult 或 PartialViewResult 的代码,但这会出现在很多地方,因此看起来过滤器的使用很好。我尝试在 IResultFilter 的两种方法中执行此操作,但没有看到输出发生变化。
如果这是不可能的,那么我将考虑在我的基本控制器中创建一些名为 ViewOrPartial 之类的方法,我可以调用它们而不是 View,但我想在放弃 Filter (或类似的方法)之前寻求更广泛的智慧。
谢谢, 马修
更新:看来我所尝试的和现在基于 Darin 代码的工作之间至少有一个区别是我重写了 OnResultExecuting (并且我也尝试过 OnResultExecuted),而 Darin 的代码重写了 OnActionExecuted。这看起来很奇怪还是我可能忽略了其他事情?我很高兴它能工作,但将它附加到 IResultFilter 接口似乎更有意义。我将不得不更多地研究这两个接口的意图。
If I create an controller method that returns ActionResult, then call View() at the end, is there any way to have a Filter (or something simular) change the returned result from the ViewResult emitted by View() to a PartialViewResult based on conditions in the Request?
Clearly I can have code in the controller method itself that returns the ViewResult or PartialViewResult, but this comes up in a number of places so it seems like a good use of a Filter. I tried doing this in both methods of the IResultFilter and saw no change in the output.
If this is not possible then I will look at creating some methods in my base controller called something like ViewOrPartial that I can call instead of View, but I wanted to seek broader wisdom before giving up on the Filter (or something like it) approach.
Thanks,
Matthew
Update: So it appears that at least one difference between what I had tried and what is now working based on Darin's code is that I had overridden OnResultExecuting (and I had also tried OnResultExecuted) and Darin's code overrides OnActionExecuted. Does that seem odd or am I perhaps overlooking something else? I am delighted to have it working but it seemed to make more sense that to attach it to the IResultFilter interface. I will have to look into the intention of the two interfaces more.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这是可能的:
然后装饰:
Yes, it is possible:
Then decorate: