Tuesday, 22 March 2022

Model Binding & Validation

 # Model Binding & Validation

1. Model binding maps data in an HTTP request to controller action method parameters
2. The action parameters may be simple types such as integers, strings, etc or complex types like Customer, Employee, Order etc.
3. Model binding is great, because without it we have to write lot of custom code to map request data to action method parameters which is not only tedious but also error prone.
4. To bind the request data to the controller action method parameters, model binding looks for data in the HTTP request in the following places in the order specified below.

    Form values
    Route values
    Query strings
    
## Model validation

1. Use ModelState.IsValid property to check if validation has failed or succeeded
If validation has failed we return the same view so the user can provide the required data and resubmit the form.
 public IActionResult Create(Employee employee)
{
    if (ModelState.IsValid)
    {
        Employee newEmployee = _employeeRepository.Add(employee);
        return RedirectToAction("details", new { id = newEmployee.Id });
    }
    return View();
}

## Displaying Model Validation Errors

1. To display a summary of all validation errors use asp-validation-summary tag helper on a <div> element as shown below.

<div asp-validation-summary="All">
</div>

## ASP.NET Core Built-in Model Validation Attributes

The following are some of the common built-in validation attributes in ASP.NET Core
Attribute     Purpose
Required     Specifies the field is required
Range     Specifies the minimum and maximum value allowed
MinLength     Specifies the minimum length of a string
MaxLength     Specifies the maximum length of a string
Compare     Compares 2 properties of a model. For example compare Email and ConfirmEmail properties
RegularExpression     Validates if the provided value matches the pattern specified by the regular expression

## Display Attribute

1. If you want the label to display Office Email instead, use the Display attribute
  [Display(Name = "Office Email")]
    public string Email { get; set; }
    
## Using Multiple Model Validation Attributes

1.  [Display(Name = "Office Email")]
    [RegularExpression(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$",
        ErrorMessage = "Invalid email format")]
    [Required]
    public string Email { get; set; }
    

No comments:

Post a Comment

Search This Blog

Creating your first "Alexa" Skill

Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...