29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

the problem (Please enter your name).<br />

I can check to see whether the model binder was able to assign a value to a property by using the<br />

ModelState.IsValidField property. I do this for the Date property to make sure that the model binder was able<br />

to parse the value the user submitted; there is no point performing additional checks or reporting additional errors if no value could<br />

be parsed from the request data.<br />

After I have validated all the properties in the model object, I read the ModelState.IsValid property to see whether<br />

there were errors. This method returns true if I called the Model.State.AddModelError method during the<br />

checks or if the model binder had any problems creating the Appointment object:<br />

...<br />

if (ModelState.IsValid) {<br />

// statements to store new Appointment in a<br />

// repository would go here in a real project<br />

return View("Completed", appt);<br />

} else {<br />

return View();<br />

}<br />

...<br />

I know I have a valid Appointment object if there are no problems reported by the IsValid property and I can render<br />

the Completed.cshtml view (and, in a real project, store the Appointment object in the repository). If the<br />

IsValue property returns false, then I know that I have a problem, which I deal with by calling the View method to<br />

render the default view.<br />

Displaying Validation Errors to the User<br />

It may seem odd to deal with a validation error by calling the View method, but the templated view helpers that I used to<br />

generate input elements in the MakeBooking.cshtml view check the view model for validation errors.<br />

The helpers add a CSS class called input-validation-error to the input elements if an error has been<br />

reported for the corresponding properties, which is why I added these CSS styles to the layout when I created the example<br />

project:<br />

...<br />

.input-validation-error { border: 2px solid #f00; background-color: #fee;<br />

}<br />

input[type="checkbox"].input-validation-error { outline: 2px solid #f00; }<br />

...<br />

The first style creates the effect of setting a red border and a pink background on any element for which there is an error. The<br />

second style applies a red border to checkbox elements. These elements are hard to style and usually require special attention. You<br />

can test the explicit validation approach by starting the application, navigating to the /Home/MakeBooking URL, and<br />

clicking the Make Booking button without entering any data in the form. The result is shown in Figure 25-2.<br />

667

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!