15 error handling
Upcoming SlideShare
Loading in...5
×
 

15 error handling

on

  • 976 views

 

Statistics

Views

Total Views
976
Views on SlideShare
976
Embed Views
0

Actions

Likes
0
Downloads
18
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    15 error handling 15 error handling Presentation Transcript

    • Data Validationin ASP.NET MVCGIGO-prevention for thenew age
    • 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.
    • 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.
    • 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
    • Data annotations1.  Required2.  StringLength3.  RegularExpression4.  Range5.  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 dont 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 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);!
    • Client-side validation code isgenerated automatically›  Why?›  In what language?
    • Hands-on data annotations
    • 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); }!
    • 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
    • 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
    • The Custom Attributepublic 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 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
    • 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