ASP.NET MVC comes with nice features to aid model validation. Unfortunately, you are still stuck writing boilerplate code on all the data entry actions. The boilerplate code looks something like:
public ActionResult DoSomething(Foo value) |
The common desired behavior is that when the submitted model is invalid the view is immediately returned so the user can fix erroneous entries. But since the flow is such that a value needs to be returned, you can’t just refactor this into a common method.
What to do? Lets implement DRY (don’t repeat yourself. Duh! just did..) based on ActionFilterAttribute
.
public class ValidateModelAttribute : ActionFilterAttribute |
This custom attribute uses the same mechanism the Controller
would have used and relies on model attributes to signal data fitness.
A straightforward behavior returning the user to the same form (view) is sufficient in most cases:
[ ] |
The total lines of code saved grow as you add many more actions (as my projects tend to gain momentum), and is quite significant.