Below I’m going to be using VS 2010 to implement the above scenario using ASP. You could also implement the exact same scenario using VS 2008 and ASP. We’ll begin by adding a simple “Person” class to a new ASP.
NET MVC 2 project that looks like below: It has four properties (implemented using C#’s automatic property support, which VB in VS 2010 now supports too – woot! We’ll then add a “Friends Controller” controller class to our project that exposes two “Create” action methods.
To enable this, all we need to do is to add two Java Script references to our view, and write one line of code: When we add these three lines, ASP.The benefit of implementing the rules within our Person object is that this will ensure that the validation will be enforced via any scenario within our application that uses the Person object (for example: if we later added an edit scenario).This will help ensure that we keep our code DRY and avoid repeating rules in multiple places. NET MVC 2 enables developers to easily add declarative validation attributes to model or viewmodel classes, and then have those validation rules automatically be enforced whenever ASP.Notice below how it takes advantage of the new strongly-typed HTML helpers in ASP.NET MVC 2 (enabling better intellisense and compile time checking support): And now when we run the application and hit the URL we’ll get a blank form that we can enter data into: Because we have not implemented any validation within the application, though, nothing prevents us from entering bogus input within the form and posting it to the server.The form is also preserving the input data the user originally entered – so that they don't have to refill anything. To understand this behavior, let’s look at the Create action method that handles the POST scenario for our form: When our HTML form is posted back to the server, the above method will be called.Because the action method accepts a “Person” object as a parameter, ASP.Specifically, let’s implement a “Create” form that enables a user to enter friend data: We want to ensure that the information entered is valid before saving it in a database – and display appropriate error messages if it isn’t: We want to enable this validation to occur on both the server and on the client (via Java Script).We also want to ensure that our code maintains the DRY principle (“don’t repeat yourself”) – meaning that we should only apply the validation rules in one place, and then have all our controllers, actions and views honor it.Let’s now update our application to enforce some basic input validation rules.We’ll implement these rules on our Person model object – and within our Controller or our View.