How can I get reference to ModelState property in my ActionFilter?
This is my class which is basically used for UnitForWork pattern i.e save everything in a transaction:
public class TestFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
if (filterContext.HttpContext == null)
throw new NullReferenceException("null");
else
{
ObjectContext objectContext =开发者_JS百科 (ObjectContext)filterContext.HttpContext.Items
[ObjectContextManager.TestContext];
if (objectContext != null)
{
objectContext.SaveChanges();
}
}
}
}
This works fine. However, I also want to make sure that it is only saved if the ModelState.IsValid property is true in my action method. How can I do so?
filterContext.Controller
gives you reference of ControllerBase
rather than Controller
. if you cast it to Controller
it will give you access to ModelState
which is a public property of controller class like
var val = ((Controller)filterContext.Controller).ModelState.IsValid;
Currently, i have no idea what are the implications of this casting. Please inquire a bit about consequences before using.
UPDATE:
you can also access Modelstate property like
filterContext.Controller.ViewData.ModelState
and it involves no casting
精彩评论