1.

What are Validation Annotations?

Answer»

In ASP.NET MVC data Annotation are built in VALIDATION which  is applied on the modal class property and render it on the view in the validation summary

The DataAnnotations attributes included in System.ComponentModel.DataAnnotations namespace

Different types of data annotations are :

  1. Required
  2. String Length
  3. Range
  4. Regular Expression
  5. Credit Card
  6. Custom Validation
  7. Email Address
  8. File Extension
  9. Max Length
  10. Min Length
  11. Phone

Eg. 

public class Student

{ public int StudentId { get; set; } [Required] public string StudentName { get; set; } [Range(5,50)] public int Age { get; set; } }

In the above-stated example, we have the Required data annotation which implies that this field must be required in every scenario if the user left this modal property empty then it will give the default error message. In the same way, we can use the range to find the age property. This will validate and display an error message if the user has either not entered Age or entered an age less than 5 or more than 50.

Eg.

namespace MVC_BasicTutorials.Controllers { public class StudentController : Controller { public ActionResult Edit(int id) { VAR std = studentList.Where(s => s.StudentId == StudentId) .FirstOrDefault(); return View(std); } [HttpPost] public ActionResult Edit(Student std) { if (ModelState.IsValid) { //write code to update student return RedirectToAction("Index"); } return View(std); } } }

In this Modal STATE will check whether the data is valid is true and it will update in the database and if not then it will return the same data in the Edit View

ModelState.IsValid DETERMINES that whether submitted values satisfy all the DataAnnotation validation attributes applied to model properties.

Eg  In the View the Data Annotation for the modal property will look like this

<div class="form-group"> @Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" }) </div> </div>

The validation Summary helper method will display the error message, ValidationMessageFor is RESPONSIBLE to display an error message for the specified field.



Discussion

No Comment Found