The goal of this tutorial is to explain one approach to performing validation in an ASP. You learn how to prevent someone from submitting an HTML form without providing values for required form fields. Controllers { public class Home Controller : Controller { private Movies DBEntities _db = new Movies DBEntities(); public Action Result Index() { return View(_db. To List()); } public Action Result Create() { return View(); } [Accept Verbs(Http Verbs.In this tutorial, you learn how to perform validation by using the IError Data Info interface. Post)] public Action Result Create([Bind(Exclude = "Id")] Movie movie To Create) { // Validate if (! Is Valid) return View(); // Add to database try { _db. Save Changes(); return Redirect To Action("Index"); } catch { return View(); } } } } The Home controller class in Listing 1 contains two Create() actions.

validating columns-1validating columns-76

The second Create() action is invoked when the form displayed by the first Create() action is submitted to the server.

Notice that the second Create() action contains the following lines of code: The Is Valid property returns false when there is a validation error.

In that case, the Create view that contains the HTML form for creating a movie is redisplayed.

The Movie class is generated by the Entity Framework. That means that we can add another partial class with the same name to extend the functionality of the Movie class. Any methods or properties that you add to this class become part of the Movie class generated by the Entity Framework.

You can take advantage of these partial methods to add validation logic to the Movie class.

The update Movie class in Listing 3 verifies that the Title and Director properties are assigned nonempty values.

A partial method is a method defined in a class that you are not required to implement. Add("Director", "Director is required."); } } } For example, if you attempt to assign an empty string to the Title property, then an error message is assigned to a Dictionary named _errors.

You can see the code for the Movie class if you expand the Movies file in the Solution Explorer window and open the Movies DBModel. We’ll add our validation logic to the new partial class. When the Entity Framework generates an entity class, the Entity Framework adds partial methods to the class automatically.

The Entity Framework generates On Changing and On Changed partial methods that correspond to each property of the class.

In the case of the Movie class, the Entity Framework creates the following methods: The On Changing method is called right before the corresponding property is changed.

The On Changed method is called right after the property is changed.