15 error handling

Post on 10-May-2015

688 views 0 download

Tags:

Transcript of 15 error handling

Data Validation in ASP.NET MVC GIGO-prevention for the new age

Where should validation happen? � Controller?

�  But this is business logic, right?

� Model? �  By this time it has already gone through the

view and the controller.

� View? �  Shouldn’t have business logic in the view.

Validation should transcend them all! �  It needs to live in all three places, � View

�  Notifying user that an error has occurred �  Doing client-side validation when possible

� Model �  Business and data rules

� Controller �  Getting the error from the model and

passing it to the view.

Data Annotations to the rescue! � Setting a simple decorator in the business

model � Generates client-side JavaScript when it

can � Hooks built-in to the controller to transfer

back-and-forth � All transparent to the user � One line of code is all it takes

Data annotations

1.  Required 2.  StringLength 3.  RegularExpression 4.  Range 5.  Compare

Required [Required]![DisplayName("New password")]!public string NewPass { get; set; }!

StringLength �  [StringLength(50, MinimumLength=10)] � public string StreetAddress{ get; set; }

RegularExpression // Allow up to 40 uppercase and lowercase !// characters. Use custom error.![RegularExpression(@”^[a-zA-Z ]+$", ! ErrorMessage=”Only letters are allowed.")]!public string JobTitle;!

Range [Range(0.0, 50.0, ! ErrorMessage = "Weight between 0 & 50")]!public double ShippingWeight{ get; set; }!

Compare [Required] !public string NewPassword { get; set; }!![Required]![Compare("NewPassword", ! ErrorMessage = "Passwords don't match.")]!public string ConfirmPassword { get; set; }!

How to code the model � You just saw example of them. � Those were all code from the model or

viewmodel.

How to code the view @using (Html.BeginForm()) {! @Html.ValidationSummary(true, "Fail. Try again")! @Html.TextBoxFor(m => m.UserName)! @Html.ValidationMessageFor(m => m.UserName)! @Html.PasswordFor(m => m.Password)! @Html.ValidationMessageFor(m => m.Password)! @Html.CheckBoxFor(m => m.RememberMe)! @Html.LabelFor(m => m.RememberMe)! <input type="submit" value="Log On" />!}!

How to code the controller if (ModelState.IsValid) {! if (MembershipService.ValidateUser())! {! FormsService.SignIn();! if (!String.IsNullOrEmpty(returnUrl))! return Redirect(returnUrl);! else! return RedirectToAction("Index", "Home");! }! else! {! ModelState.AddModelError("", Bad Data!!");! }!}!// If we got this far, something failed,!// redisplay form!return View(model);!

Client-side validation code is generated automatically � Why? �  In what language?

Hands-on data annotations

We can disable client-side validation if we want to � We can turn it off if we want in web.config <appSettings>! <add key="ClientValidationEnabled" ! value="true" />! <add key="UnobtrusiveJavaScriptEnabled" ! value="true" />!</appSettings>!�  And re-enable it in each view @{ Html.EnableClientValidation(true); }!

Note that DataTypes are not validations (strictly speaking) [Required]![DataType(DataType.Email)]![DisplayName("Email Address")]!public string Email { get; set; }!� They are only used when generating templates � You probably want a Regular Expression

validation

If our needs can’t be met by other annotations, we can write custom annotations � Write class that inherits from

ValidationAttribute � Override IsValid() � Return "success" if valid and the failure

reason if not � Use your new attribute

The Custom Attribute public class SampleAttribute : ValidationAttribute!{! public override ValidationResult IsValid(object value)! {!

if ( /* some criteria */ )! return ValidationResult.Success;! else! return new ValidationResult("Failure message");!

}!

}!

Hands-on custom data annotations

Conclusion � Data Annotations enable really easy data

validations so you don't need to write a lot of JavaScript

� Based on the industry-wide accepted jQuery validation framework

� They use server-side code and generate client-side jQuery/JavaScript

Further study � Nice tutorial

�  http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

� Microsoft's tutorial �  http://msdn.microsoft.com/en-us/

vs2010trainingcourse_aspnetmvccustomvalidation.aspx