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

1

0

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?

enter image description here


This is how I am register the above Action Filter:

[HttpPost]
[CustomPermissionCheck]
public ActionResult UpdateBranch(MyViewModel myViewModel)
{
    if (ModelState.IsValid)
    {
        // so something 
    }
    return View();
}
Genaro answered 9/5, 2020 at 9:7 Comment(1)
I have posted the same question on ASP.NET MVC forumGenaro
M
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

Motley answered 11/5, 2020 at 7:48 Comment(3)
Thanks a lot, that worked... I am still not sure why the ViewData.Model is not available? Isn't it Model Binder's job to populate ViewData.Model?Genaro
I'm not an expert but ViewData is a dictionary which can contain key-value pairs and is often used to transfers data from the Controller to View (not vice-versa). When compares to Model in model binding, they are just ... two different things...Motley
I had seen the link that you have added to your answer... but that link does not contain the solution that you have included in your answer...Genaro

© 2022 - 2024 — McMap. All rights reserved.