I am using the web API using REST for the ASP.NET MVC framework (MVC 2). I want to encapsulate this code, ideally, in ActionFilterAttribute (?), So that I can decorate specific actions that always follow the same logic:
if (!ModelState.IsValid) {
return View(
new GenericResultModel(){ HasError=True, ErrorMessage="Model is invalid."});
}
I really don't want to copy and paste this boilerplate code into every controller action where I need to do this.
In this web API scenario, I need to do something similar so that the caller can get the result in the form of JSON or POX and see that there is an error. In the ASPX view, obviously, I will not need something like this, since the validation controls will take care to notify the user about the problem. But I don't have an ASPX view - I only return JSON or POX data serialized from my model.
I started with this code in ActionFilter, but I'm not sure what to do next (or even if this is the right starting point):
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool result = filterContext.Controller.ViewData.ModelState.IsValid;
if (!result)
{
GenericResultModel m = new GenericResultModel() { HasError = true };
}
base.OnActionExecuting(filterContext);
}
How to do it?
source
share