Data Annotations can be used to perform validation for every field in a GridView in ASP.NET MVC. By defining validation rules directly in your model with these annotations, you can make sure that user input is validated both on the client and server sides. This is the methodical way to accomplish it:
Step 1: Update Your Model with Data Annotations
In your Employee
model class, apply the appropriate Data Annotation attributes to each property to enforce validation rules. Here’s how you can modify the Employee.cs
model:
csharp
using System.ComponentModel.DataAnnotations;
public class Employee {
[Key]
public int EmpId { get; set; }
[Required(ErrorMessage = “First Name is required”)]
[StringLength(100, MinimumLength = 2, ErrorMessage = “First Name must be between 2 and 100 characters”)]
public string EmpFirstName { get; set; }
[Required(ErrorMessage = “Last Name is required”)]
[StringLength(100, MinimumLength = 2, ErrorMessage = “Last Name must be between 2 and 100 characters”)]
public string EmpLastName { get; set; }
[Required(ErrorMessage = “Address is required”)]
[StringLength(255, ErrorMessage = “Address cannot exceed 255 characters”)]
public string Address { get; set; }
[Required(ErrorMessage = “Sex is required”)]
public string Sex { get; set; }
[Required(ErrorMessage = “Email is required”)]
[EmailAddress(ErrorMessage = “Invalid Email Address”)]
[StringLength(100, ErrorMessage = “Email cannot exceed 100 characters”)]
public string Email { get; set; }
[Required(ErrorMessage = “Contact Number is required”)]
[RegularExpression(@”^\d{10}$”, ErrorMessage = “Contact Number must be 10 digits”)]
public string ContactNo { get; set; }
}
Explanation of Annotations Used:
- [Required]: Ensures the field is not empty.
- [StringLength]: Sets limits on the length of the string.
- [EmailAddress]: Validates that the input is in the correct email format.
- [RegularExpression]: Validates the format of the contact number.
Step 2: Update the Views to Display Validation Messages
In your Index.cshtml
view, ensure that you display validation messages. Here’s how you can modify the form for adding new employees and editing existing ones:
xml
@model IEnumerable<Employee>
<h2>Employees</h2>
@using (Html.BeginForm(“Create”, “Employee”, FormMethod.Post)) {
@Html.AntiForgeryToken()
<h3>Add New Employee</h3>
<div>
@Html.LabelFor(m => m.EmpFirstName)
@Html.TextBoxFor(m => m.EmpFirstName, new { @class = “form-control” })
@Html.ValidationMessageFor(m => m.EmpFirstName, “”, new { @class = “text-danger” })
</div>
<div>
@Html.LabelFor(m => m.EmpLastName)
@Html.TextBoxFor(m => m.EmpLastName, new { @class = “form-control” })
@Html.ValidationMessageFor(m => m.EmpLastName, “”, new { @class = “text-danger” })
</div>
<div>
@Html.LabelFor(m => m.Address)
@Html.TextBoxFor(m => m.Address, new { @class = “form-control” })
@Html.ValidationMessageFor(m => m.Address, “”, new { @class = “text-danger” })
</div>
<div>
@Html.LabelFor(m => m.Sex)
@Html.TextBoxFor(m => m.Sex, new { @class = “form-control” })
@Html.ValidationMessageFor(m => m.Sex, “”, new { @class = “text-danger” })
</div>
<div>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email, new { @class = “form-control” })
@Html.ValidationMessageFor(m => m.Email, “”, new { @class = “text-danger” })
</div>
<div>
@Html.LabelFor(m => m.ContactNo)
@Html.TextBoxFor(m => m.ContactNo, new { @class = “form-control” })
@Html.ValidationMessageFor(m => m.ContactNo, “”, new { @class = “text-danger” })
</div>
<input type=”submit” value=”Add Employee” class=”btn btn-primary” />
}
<table class=”table”>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>Sex</th>
<th>Email</th>
<th>Contact No</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var emp in Model) {
<tr>
<td>@emp.EmpFirstName</td>
<td>@emp.EmpLastName</td>
<td>@emp.Address</td>
<td>@emp.Sex</td>
<td>@emp.Email</td>
<td>@emp.ContactNo</td>
<td>
@Html.ActionLink(“Edit”, “Edit”, new { id = emp.EmpId }) |
@Html.ActionLink(“Delete”, “Delete”, new { id = emp.EmpId })
</td>
</tr>
}
</tbody>
</table>
Step 3: Enable Client-Side Validation
To enable client-side validation, ensure you have the necessary JavaScript libraries included in your layout file (e.g., _Layout.cshtml
):
xml
<script src=”~/Scripts/jquery.validate.min.js”></script>
<script src=”~/Scripts/jquery.validate.unobtrusive.min.js”></script>
By enabling the validation attributes to function on the client side, these scripts enable users to receive feedback right away without having to submit anything back to the server.
Step 4: Handle Server-Side Validation
In your controller, you should check ModelState.IsValid
before processing the data:
csharp
[HttpPost]
public ActionResult Create(Employee employee) {
if (ModelState.IsValid) {
repository.AddEmployee(employee);
return RedirectToAction(“Index”);
}
return View(employee); // Return the same view with validation errors
}
This guarantees that the user will see the relevant error messages without losing the data they submitted in the event that any validation fails.
These methods will help you to ensure data integrity and improve user experience by successfully implementing validation for every field in the GridView of your ASP.NET MVC application.