I’m developing something like wizard with steps (controllers) and uses DerivedModel1, DerivedModel2,etc which is inherits from BaseModel and extends them with extra properties.
Models – only data, without business logic. All logic performed by services in controllers action for example _step1Service.GetRelated(model.id).
Now I want to not just validate Model (for this case there is ValidationAttribute) but fix invalid data in BaseModel:
public class BaseModel
{
public DateTime StartDate {get;set;}
}
StartDate should be greater than today. User can select invalid date and instead of validation error application should fix this value (reset to default?).
In my first attempt I added service for validating/correcting StartDate and call in each Action:
public ActionResult Index(DerivedModel1 model)
{
_svc.fixModel(model);
if(!ModelState.IsValid)
{
return View();
}
... do stuff with valid data
}
But don’t like that, because have to add this line to each controller and action.
Then I add this correction to StartDate setter. It’s looks better, but this breaks popular MVC paradigm that all logic should be in controller (or maybe i misunderstood something?)
I was thinking about possible solutions of this problem: ActionFilterAttribute, custom ModelBinder? But not sure is this right way and whether it work.
What you think about that?
you must implement IModelBinder to achieve this.
first define your custom model binder like this:
then register your custom model binder such:
and your controller :