How many times did you write a code like this:

Workflow is usually this: 

  • Try to validate user input

    • If error, return same view with error messages

  • Invoke business logic, map data to persistence model

  • Try to save data

    • If error, log to db, return view with user-readable error message (this is generic approach, true, in real app we would probably try to check what kind of error was returned and then do something specific)

  • Redirect somewhere (we are in Post-Redirect-Get loop)

To avoid of repetition of some steps there we can decorate Save actions with our special attribute!

Here's the whole filter, with all the code comments which hopefully explains how it works.

Usage is simple, just decorate your POST action with [ValidateModel] attribute, and then you can remove if(!ModelState.IsValid) checks, and also exception catch if there's any.

Post comment