15 error handling


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

15 error handling

  1. 1. Data Validationin ASP.NET MVCGIGO-prevention for thenew age
  2. 2. Where should validationhappen?›  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.
  3. 3. Validation should transcendthem all!›  Itneeds 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.
  4. 4. Data Annotations to therescue!›  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
  5. 5. Data annotations1.  Required2.  StringLength3.  RegularExpression4.  Range5.  Compare
  6. 6. Required[Required]![DisplayName("New password")]!public string NewPass { get; set; }!
  7. 7. StringLength›  [StringLength(50, MinimumLength=10)]›  public string StreetAddress{ get; set; }
  8. 8. RegularExpression// Allow up to 40 uppercase and lowercase !// characters. Use custom error.![RegularExpression(@”^[a-zA-Z ]+$", ! ErrorMessage=”Only letters are allowed.")]!public string JobTitle;!
  9. 9. Range[Range(0.0, 50.0, ! ErrorMessage = "Weight between 0 & 50")]!public double ShippingWeight{ get; set; }!
  10. 10. Compare[Required] !public string NewPassword { get; set; }!![Required]![Compare("NewPassword", ! ErrorMessage = "Passwords dont match.")]!public string ConfirmPassword { get; set; }!
  11. 11. How to code the model›  You just saw example of them.›  Those were all code from the model or viewmodel.
  12. 12. 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" />!}!
  13. 13. How to code the controllerif (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);!
  14. 14. Client-side validation code isgenerated automatically›  Why?›  In what language?
  15. 15. Hands-on data annotations
  16. 16. We can disable client-sidevalidation 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); }!
  17. 17. Note that DataTypes are notvalidations (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
  18. 18. If our needs can’t be met byother annotations, we can writecustom annotations›  Writeclass that inherits from ValidationAttribute›  Override IsValid()›  Return "success" if valid and the failure reason if not›  Use your new attribute
  19. 19. The Custom Attributepublic class SampleAttribute : ValidationAttribute!{! public override ValidationResult IsValid(object value)! {! if ( /* some criteria */ )! return ValidationResult.Success;! else! return new ValidationResult("Failure message");! }!}!
  20. 20. Hands-on custom data annotations
  21. 21. Conclusion›  Data Annotations enable really easy data validations so you dont 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
  22. 22. Further study›  Nice tutorial ›  http://bradwilson.typepad.com/blog/ 2010/10/mvc3-unobtrusive-validation.html›  Microsofts tutorial ›  http://msdn.microsoft.com/en-us/ vs2010trainingcourse_aspnetmvccustomvali dation.aspx