如何使用类型的视图时设置在ActionFilterAttribute模型数据 [英] How to set model data in ActionFilterAttribute when using a typed view
问题描述
我用,所有的ViewModels继承一个类BaseViewModel强类型的意见。
I use strongly typed views where all ViewModels inherit a class BaseViewModel.
在该装饰所有控制器我想用模型的ActionFilter。
In an ActionFilter that decorates all Controllers I want to use the Model.
现在我只能访问它是这样的:
Right now I can only access it like this:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ViewModelBase model = (ViewModelBase)filterContext.ActionParameters["viewModel"];
base.OnActionExecuting(filterContext);
}
问题是,我必须知道密钥视图模型。最关键的是视图模型,因为在我的控制器我用:
The problem is, that I have to know the key "viewModel". The key is viewModel, because in my controller I used:
回归
视图(MyView的
视图模型)
return View("MyView", viewModel)
有没有存取权限模型一个更安全的方式?
Is there a safer way to acces the Model?
推荐答案
OnActionExecuting之前执行的动作作品 - 这样,模型设置为null。你可以访问你的OnActionExecuted ViewData的(或ViewData.Model):
OnActionExecuting works just before your Action is executed - thus the Model is set to null. You could access your ViewData (or ViewData.Model) in OnActionExecuted:
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var model = filterContext.Controller.ViewData.Model as YourModel;
...
}
希望这有助于
这篇关于如何使用类型的视图时设置在ActionFilterAttribute模型数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!