If validation fails, the Create form is redisplayed with the error messages. The Edit() action needs to perform exactly the same validation as the Create() action.
Instead of duplicating the same validation code, we should refactor the Contact controller so that both the Create() and Edit() actions call the same validation method.
In this second iteration of the Contact Manager application, we add basic form validation.
We prevent people from submitting a contact without entering values for required form fields.
Note The feedback system for this content will be changing soon. If content within a comment thread is important to you, please save a copy.
For more information on the upcoming change, we invite you to read our blog post.
We'll take advantage of several software design principles to enable us to create a more loosely coupled, and more maintainable, application.For example, you can use the Microsoft Enterprise Library Validation Application Block (VAB) to implement the validation logic for your ASP. To learn more about the Validation Application Block, see: Let s start by adding validation logic to the Create view.Fortunately, because we generated the Create view with Visual Studio, the Create view already contains all of the necessary user interface logic to display validation messages. Listing 1 - \Views\Contact\Notice the call to the Html.Note The Update Model() method adds error messages to Model State automatically when there is an error assigning the value of a form field to a property.For example, if you attempt to assign the string "apple" to a Birth Date property that accepts Date Time values, then the Update Model() method adds an error to Model State.In this iteration, to keep things simple, we write all of the validation code by hand.Instead of writing the validation code ourselves, we could take advantage of a validation framework.The Validation Message() helper displays an individual validation error message.In the case of Listing 1, an asterisk is displayed when there is a validation error. Text Box() helper automatically renders a Cascading Style Sheet class when there is a validation error associated with the property displayed by the helper. Text Box() helper renders a class named input-validation-error. NET MVC application, a style sheet named is created in the Content folder automatically.In general, this is not the recommended way to add validation to an ASP. A better approach is to place an application s validation logic in a separate service layer.In the next iteration, we refactor the Contact Manager application to make the application more maintainable.