views:

144

answers:

1

I followed these tutorials:

http://www.asp.net/learn/mvc/tutorial-39-cs.aspx http://schotime.net/blog/index.php/2009/03/31/integrating-xval-validation-with-linq-to-sql/

in order to enforce data validation using Data Annotation for a LINQ-To-SQL-generated class. The metadata class looks like this:

[MetadataType(typeof(PositionValidation))]
public partial class Position
{
}

public class PositionValidation
{
    [Required]
    public string Title { get; set; }
}

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

if (ModelState.IsValid)
{
    _positions.AddPosition(newPosition);
    return RedirectToAction("List");
}

If I leave out the check for valid ModelState, it will attempt to add it to the database, even if Title is empty. As a result, I get an entry with a blank title (this applies to edits as well).

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

A: 

So in other words (please let me know if I am wrong), you expected that your action was NOT executed at all if the Data Annotation validation failed. This was the only way to omit the if(Model.IsValid) statement.

Your assumption is not correct, and this is by design. It's a very nice feature in fact, not a nuisance. You add only a line of code, to check whether there are errors, and in return you get the possibility to:

  • add your own errors which come from the business logic, so they are displayed to the user immediately, and not upon the next submission, when the DA is ok
  • reset errors or customize errors
  • redirect to some other view, or do any action (e.g. logging) upon certain conditions
Palantir