加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何在使用类型化视图时在ActionFilterAttribute

发布时间:2020-12-16 04:17:34 所属栏目:asp.Net 来源:网络整理
导读:我使用强类型视图,其中所有ViewModel都继承了一个类BaseViewModel. 在装饰所有控制器的ActionFilter中,我想使用Model. 现在我只能像这样访问它: public override void OnActionExecuting(ActionExecutingContext filterContext) { ViewModelBase model = (V
我使用强类型视图,其中所有ViewModel都继承了一个类BaseViewModel.

在装饰所有控制器的ActionFilter中,我想使用Model.

现在我只能像这样访问它:

public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ViewModelBase model = (ViewModelBase)filterContext.ActionParameters["viewModel"];
        base.OnActionExecuting(filterContext);
   }

问题是,我必须知道密钥“viewModel”.关键是viewModel,因为在我的控制器中我用过:

return
View(“MyView”,
viewModel)

是否有更安全的方式来访问模型?

解决方法

OnActionExecuting在Action执行之前工作 – 因此Model被设置为null.您可以在OnActionExecuted中访问ViewData(或ViewData.Model):
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    var model = filterContext.Controller.ViewData.Model as YourModel;

    ...
}

希望这可以帮助

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读