Book Image

ASP.NET MVC 1.0 Quickly

By : Maarten Balliauw
Book Image

ASP.NET MVC 1.0 Quickly

By: Maarten Balliauw

Overview of this book

<p>Using WebForms has led to problems for ASP.NET developers, such as low testability and inconsistent code. These problems become increasingly relevant when trying to develop or maintain anything but the simplest web site.<br /><br />This book takes you through the ASP.NET MVC framework to help you simplify and build web applications quickly. With example applications built on best practices and with clear explanations, you will get started in no time.<br /><br />The MVC pattern is widely accepted as one of the best approaches for building modern web applications and Microsoft's new ASP.NET MVC Framework offers a fully supported way for developers to implement MVC in ASP.NET.<br /><br />This book takes you through the essential tasks to create powerful web applications as fast as possible. These essential tasks are explained clearly, with well-structured instructions. The book does not cover every single feature in detail; it provides precise information for you to get started, and takes you through the creation of an example application that covers MVC application design techniques.<br /><br />In addition to helping you write code, this book covers unit testing, to improve the stability and quality of the application you are building. It provides a quick reference to the MOQ framework to aid in unit testing. With this book, you will soon have the skills that will make you an ASP.NET developer to be reckoned with, and you will be creating applications with a speed that will astonish your colleagues and boss!</p>
Table of Contents (18 chapters)
ASP.NET MVC 1.0 Quickly
Credits
About the author
About the reviewers
Preface
ASP.NET MVC Mock Helpers

Form validation


CarTrackr contains various scenarios where form validation is performed. Let's have a look at one of these scenarios—creating a new Car. The action method New is defined in the CarController:

[AcceptVerbs("POST")]
[ValidateAntiForgeryToken]
public ActionResult New(FormCollection form)
{
Car car = new Car();
try
{
this.UpdateModel(car, new[] { "Make", "Model", "PurchasePrice", "LicensePlate", "FuelType", "Description" });
CarRepository.Add(car);
return RedirectToAction("Details", new { licensePlate = car.LicensePlate });
}
catch (RuleViolationException)
{
this.UpdateModelStateWithViolations(car, ViewData.ModelState);
return View("New", car);
}
}

When creating a new Car, the New action method of the CarController class creates a new Car instance and tries to update this object with the data received from the posted form, by using the UpdateModel method. Immediately after that, the CarRepository is instructed to add the car instance and save it to the database. Note that this method will call the EnsureValid method that is defined on the Car class. The EnsureValid method checks whether there are any violations in the car instance, and throws a RuleViolationException if any errors are present.

public void EnsureValid()
{
List<RuleViolation> issues = GetRuleViolations();
if (issues.Count != 0)
throw new RuleViolationException("Business Rule Violations", issues);
}

The GetRuleViolations method performs various checks on the car instance. Whenever a check fails, a new RuleViolation is added to a list of violations. The RuleViolation object holds the property name, the provided value and an error message.

public List<RuleViolation> GetRuleViolations()
{
List<RuleViolation> validationIssues = new List<RuleViolation>();
if (string.IsNullOrEmpty(Make))
validationIssues.Add(new RuleViolation("Make", Make, "Make should be specified!"));
if (string.IsNullOrEmpty(Model))
validationIssues.Add(new RuleViolation("Model", Model, "Model should be specified!"));
if (PurchasePrice <= 0)
validationIssues.Add(new RuleViolation("PurchasePrice", PurchasePrice, "Purchase price should be specified!"));
if (string.IsNullOrEmpty(LicensePlate))
validationIssues.Add(new RuleViolation("LicensePlate", LicensePlate, "License plate should be specified!"));
return validationIssues;
}

When the New action method of CarController catches a RuleViolationException, it calls the UpdateModelStateWithViolations method (and provides the car being added) and the ViewData ModelState dictionary. The UpdateModelStateWithViolations method copies all of the rule violations from the RuleViolationException into the ViewData ModelState dictionary. Afterwards, the CarController renders the view again, which will now display any validation issues:

Error messages in the view are displayed using ASP.NET MVC's HtmlHelper.ValidationMessage form helper, which we explained in Chapter 4, Components in the ASP.NET MVC Framework.