Understanding ASP.NET MVC Lifecycle: Why is Model not available in ActionFilter?

人走茶凉 提交于 2021-01-29 09:14:50

问题


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();
}

回答1:


Could try this to access the request model:

MyViewModel vm = context.ActionParameters.Values.OfType<MyViewModel>().SingleOrDefault();

How to get current model in action filter



来源:https://stackoverflow.com/questions/61694278/understanding-asp-net-mvc-lifecycle-why-is-model-not-available-in-actionfilter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!