I have created the following Custom Action Filter, when I try to access the Model in the following code, it is null:
publicclassCustomPermissionCheckAttribute:ActionFilterAttribute{publicoverridevoidOnActionExecuting(ActionExecutingContext context){OrganisationBaseController orgBaseController = context.ControllerasController;MyViewModel m =((Controller)context.Controller).ViewData.ModelasMyViewModel;// null// check if current user has permission to m.OrganisationIdbase.OnActionExecuting(context);}}
I am trying to understand why the Model is null? According to ASP.NET MVC Pipeline, Action
Filters are executed after Model Binding, so I am not sure why the Model is not available?
This is how I am register the above Action Filter:
[HttpPost][CustomPermissionCheck]publicActionResultUpdateBranch(MyViewModel myViewModel){if(ModelState.IsValid){// do something...}returnView();}
MyViewModel m = context.ActionParameters.Values.SingleOrDefault() as MyViewModel;
Here is the result.
Best Regards,
YihuiSun
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Member
2 Points
4 Posts
Understanding ASP.NET MVC Lifecycle: Why is Model not available in ActionFilter?
May 11, 2020 07:11 AM|HoomanBahreini|LINK
I have created the following Custom Action Filter, when I try to access the
Model
in the following code, it is null:I am trying to understand why the
Model
is null? According to ASP.NET MVC Pipeline, Action Filters are executed after Model Binding, so I am not sure why the Model is not available?This is how I am register the above Action Filter:
All-Star
58204 Points
15661 Posts
Re: Understanding ASP.NET MVC Lifecycle: Why is Model not available in ActionFilter?
May 11, 2020 02:18 PM|bruce (sqlwork.com)|LINK
The viewdata.model, is set when the viewcontext is setup via
return View(viewModel)
Contributor
2750 Points
781 Posts
Re: Understanding ASP.NET MVC Lifecycle: Why is Model not available in ActionFilter?
May 12, 2020 09:39 AM|YihuiSun|LINK
Hi, HoomanBahreini
You can get your model in the following way.
MyViewModel m = context.ActionParameters.Values.SingleOrDefault() as MyViewModel;
Here is the result.
Best Regards,
YihuiSun
Member
2 Points
4 Posts
Re: Understanding ASP.NET MVC Lifecycle: Why is Model not available in ActionFilter?
May 14, 2020 07:22 AM|HoomanBahreini|LINK
Thanks a lot,