Data validation does not provide model validation?

I followed these tutorials:

to provide data validation using data annotation for the LINQ-To-SQL generated class. The metadata class looks like this:

public partial class Position

public class PositionValidation
    public string Title { get; set; }


Validation works correctly, but only if I do this in the controller:

if (ModelState.IsValid)
    return RedirectToAction("List");


If I don't check for a valid ModelState it will try to add it to the database even if the header is empty. As a result, I get a post with an empty title (this also applies to editing).

I was under the impression that data validation also ensures that it is consistent for the model, in addition to the controller / view. Does this mean that I have to add additional code to validate in the Position class? If so, doesn't that violate DRY?


source to share

1 answer

So in other words (please let me know if I'm wrong), you expected your action to fail at all if the data annotation validation failed. This was the only way to omit the if (Model.IsValid) statement.

Your guess is wrong, and that's by design. This is a very nice feature, not a nuisance. You only add a line of code to check if there are errors, and in response, you get the option:

  • add your own errors that come from the business logic so they are shown to the user right away and not after the next view when the DA is ok.
  • reset errors or setting errors
  • redirect to another view or perform some action (like logging) under certain conditions


All Articles