Translate

What is Manual Validation?

The first approach of validation is to validate data manually for each property in view model object when user submit a form. In this process the data of the form fields will be simply used to create view model object i.e. data binding then the object will be sent to the controller to process requests. This is the responsibility of developer to validate every property by writing the validation logic in action method.

Because the data binding already occurred and view model object is created, one step in the validation process and the data type check is completed. It is important as the data type check, while not so difficult, is tedious and repetitive task which takes a lot of developer’s time.

To see how the manual validation works lets take example, in the application the feature in
which user can send messages to pet owner. The view model shown in Figure 1 represents the message which is to be sent to pet owner using form in view.

This has four properties:

1. The name of the person sending the messages (From)
2. The email address of the person sending the messages (Email)
3. The subject of messages

4. The content of the messages.

Figure 1. View Model Class to Send Messages

Next, we need a controller to work with messages. Right click on the Controller directory in Solution Explorer window and chose Add => Controller. Put name of the controller like MessageController as shown in Figure 2 and chose “Empty MVC controller” from the Template drop down list and click Add.



Figure 2. Adding the Message controller

Now add some functionality to controller to validate and send message. Following steps will add initial functionality to perform manual validation:

1. New controller has a default action method known as Index. Rename action method to Send().

2. Add new action method, called Send() and add parameter named model with type
MessageModel.

3. Decorate new Send() action method to use the [HttpPost] method. It will instruct
controller to use this particular overloaded method of Send() action method whenever the
request is made by HTTP POST.

4. First validation used to ensure that the view model object is valid. We can do it by checking IsValid property of ModelState object. ModelState.IsValid tells us about the model errors have been added to ModelState. Default model binder adds some errors for basic
type conversions (for example, if passing a non numeric for any integer).

5. If view model object is valid then we will be redirected to another action method to render ThankYou view which tell the user that the message has been sent.

6. If the model state is not valid then we need to create an error message that should be rendered in the view for informing the user that something went wrong for the data submitted. To add error, use method AddModelError of ModelState object.

All steps shown in the code shown in Figure 3 below:


Figure 3. Message Controller

The ModelState.AddModelError() method requires two parameters. First one is the specific property from view model for that the error is generated. If error is not specific for a property in view model but it is a general error. We can pass empty string (as shown in Figure 3 above).

The second parameter is error description we want to show to the user. Next, let’s examine the code of the views. To create a Send view just right click some where in first Send() action method and then choose “Add View” option. The Add View dialog box will be opened (as shown in Figure 4. Name of the view should be Send.


Figure 4. Add View dialog

Check the “Create strongly typed view” check box for creating a strongly typed view and select the MessageModel class from “Model class” drop down list. If MessageModel class is not available in the list then we need to build application first with option Build Solution available in the BUILD menu or we can use shortcut keys Ctrl + Shift + B. From the “Scaffold template” drop down list, chose “Create” and leave rest of the properties with their default values. Choosing the scaffold template instructs that the dialog to create HTML form with fields corresponding to each properties from the view model class from the view. The code for the view is shown in Figure 5 below:

Figure 5. Newly Created Send View

HTML helper method @Html.ValidationSummary(true) returns unordered list (<ul>) with all errors from the model state. If Boolean parameter is set as true then the list of errors will include only the model level errors. If it is set as false then all the errors will be added into the list. Model level errors are not specific to particular property of the view model.

For example, errors that we added with the method ModelState.AddModelError() when the IsValid property was false.

There are many @Html.ValidationMessageFor() HTML helper methods available in view, one for every field of the form. Each of those helper methods is bounded for a particular field from view model. When any error is detected in form fields then these methods will be rendered a <span> element with specific error for the field for which they are bound. These error messages will be displayed automatically in browser before form is posted to server,
courtesy of neat JavaScript code that MVC inserted into web page when the page rendered the view.

Now create ThankYou view that will be rendered when validation test get succeeded and everything is fine. Create a view that does not have any view model and name it as ThankYou. In the <h2> tag, please modify the text to say ThankYou and add any sentence in <p> tag to indicate message has been sent as shown in Figure 6 below:


Figure 6. ThankYou View

When we run the application and make request then the browser will render the view created above as shown in Figure 7 below:


Figure 7. Rendered view for the request

No comments:

Post a Comment