29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

if (ModelState.IsValidField("ClientName") &&<br />

ModelState.IsValidField("Date")<br />

&& appt.ClientName == "Joe" && appt.Date.DayOfWeek ==<br />

DayOfWeek.Monday) {<br />

ModelState.AddModelError("", "Joe cannot book appointments on<br />

Mondays");<br />

}<br />

}<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 />

Before I check to see whether Joe is trying to book on a Monday, I use the ModelState.IsValidField method to<br />

ensure that I have valid ClientName and Date values to work with. This means I will not generate a model-level error<br />

unless the previous checks on the properties have been successful. I register a model-level error by passing the empty string ("")<br />

as the first parameter to the ModelState.AddModelError method, like this:<br />

...<br />

ModelState.AddModelError("" , "Joe cannot book appointments on Mondays");<br />

...<br />

I can then update the MakeBooking.cshtml view file to use the version of the ValidationSummary helper<br />

method that takes a bool parameter to display only the model-level errors, as shown in Listing 25-10.<br />

Listing 25-10. Display Only Model-Level Errors in the MakeBooking.cshtml File<br />

@model ModelValidation.Models.Appointment<br />

@{<br />

ViewBag.Title = "Make A Booking";<br />

}<br />

Book an Appointment<br />

@using (Html.BeginForm()) {<br />

@Html.ValidationSummary(true)<br />

Your name: @Html.EditorFor(m => m.ClientName)<br />

Appointment Date: @Html.EditorFor(m => m.Date)<br />

@Html.EditorFor(m => m.TermsAccepted) I accept the terms &<br />

conditions<br />

<br />

}<br />

You can see the result of these changes in Figure 25-4, where I have entered the name Joe and specified a date, which is a<br />

Monday.<br />

671

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

Saved successfully!

Ooh no, something went wrong!