了解ASP.NET MVC生命周期:为什么模型在ActionFilter中不可用? [英] Understanding ASP.NET MVC Lifecycle: Why is Model not available in ActionFilter?
本文介绍了了解ASP.NET MVC生命周期:为什么模型在ActionFilter中不可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了以下自定义ActionFilter,当我尝试在以下代码中访问 Model
时,它为null:
公共类CustomPermissionCheckAttribute:ActionFilterAttribute{公共重写void OnActionExecuting(ActionExecutingContext context){OrganisationBaseController orgBaseController = context.Controller作为控制器;var vm =(((Controller)context.Controller).ViewData.Model as MyViewModel;//空值//检查当前用户是否具有vm.OrganisationId的权限base.OnActionExecuting(context);}}
我试图理解为什么 Model
为null?根据
这是我注册上述动作过滤器的方式:
[HttpPost][CustomPermissionCheck]公共ActionResult UpdateBranch(MyViewModel myViewModel){如果(ModelState.IsValid){//这样的事情}返回View();}
解决方案
可以尝试使用此方法访问请求模型:
MyViewModel vm = context.ActionParameters.Values.OfType< MyViewModel>().SingleOrDefault();
I have created the following Custom ActionFilter, when I try to access the Model
in the following code, it is null:
public class CustomPermissionCheckAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
OrganisationBaseController orgBaseController = context.Controller as Controller;
var vm = ((Controller)context.Controller).ViewData.Model as MyViewModel; // null
// check if current user has permission to vm.OrganisationId
base.OnActionExecuting(context);
}
}
I am trying to understand why the Model
is null? According to ASP.NET MVC Lifecycle, ActionFilters are executed after Model Binder, so I am not sure why the Model is not available?
This is how I am register the above Action Filter:
[HttpPost]
[CustomPermissionCheck]
public ActionResult UpdateBranch(MyViewModel myViewModel)
{
if (ModelState.IsValid)
{
// so something
}
return View();
}
解决方案
Could try this to access the request model:
MyViewModel vm = context.ActionParameters.Values.OfType<MyViewModel>().SingleOrDefault();
How to get current model in action filter
这篇关于了解ASP.NET MVC生命周期:为什么模型在ActionFilter中不可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文