Friday, March 25, 2011

Removing validation errros of unused fields ASP.NET MVC

We are using ORM tools to create our Model objects and we may not be using all the properties in the page, So validation is going to be thrown irrespective of the properties used in the page.

In these scenarios we can use ActionFilterAttribute. We should override the OnActionExecuting method to remove the validations for un used properties.

public class UsedFieldsOnlyValidationAttribute : ActionFilterAttribute{

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var modelState = filterContext.Controller.ViewData.ModelState;
var valueProvider = filterContext.Controller.ValueProvider;

var keysWithNoIncomingValue = modelState.Keys.Where(x => !valueProvider.ContainsPrefix(x));
foreach (var key in keysWithNoIncomingValue)
{
modelState[key].Errors.Clear();
}
}
}

No comments:

Post a Comment