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();
}
Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137
  • I have posted the same question on [ASP.NET MVC forum](https://forums.asp.net/p/2166817/6304277.aspx?p=True&t=637247527007872847#_=_) – Hooman Bahreini May 11 '20 at 07:12

1 Answers1

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

Rohim Chou
  • 907
  • 10
  • 16
  • 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? – Hooman Bahreini May 11 '20 at 08:40
  • 1
    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... – Rohim Chou May 11 '20 at 09:06
  • I had seen the [link](https://stackoverflow.com/questions/38895830/how-to-get-current-model-in-action-filter) that you have added to your answer... but that link does not contain the solution that you have included in your answer... – Hooman Bahreini May 11 '20 at 09:21