How do I enable server-side validation for GridView in Asp.net MVC ?

How do I enable server-side validation for GridView in Asp.net MVC ?

These procedures, which apply to several GridView implementations like Syncfusion, DevExpress, or Telerik, can be used to enable server-side validation for a GridView in an ASP.NET MVC application. Here’s a basic strategy:

Step 1: Define Your Model with Data Annotations

First, ensure that your model class includes the necessary Data Annotation attributes to enforce validation rules. For example, if you have an Employee model, it might look like this:

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”)]

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; }

}

Step 2: Set Up the Controller for Validation

In your controller, implement the actions for handling the CRUD operations. Validate the model state when data is submitted:

csharp

[HttpPost]

public ActionResult Create(Employee employee) {

if (ModelState.IsValid) {

// Save employee to the database

return RedirectToAction(“Index”);

}

return View(employee); // Return to the view with validation errors

}

[HttpPost]

public ActionResult Edit(Employee employee) {

if (ModelState.IsValid) {

// Update employee in the database

return RedirectToAction(“Index”);

}

return View(employee); // Return to the view with validation errors

}

Step 3: Implement Server-Side Validation Logic in the GridView

For Syncfusion Grid

  1. Use the actionBegin Event: Handle the actionBegin event to perform server-side validation before saving data.

javascript

function actionBegin(e) {

if (e.requestType === ‘save’) {

e.cancel = true; // Cancel the default save action

var grid = document.getElementById(“InlineEditing”).ej2_instances[0];

// Perform server-side validation

var ajax = new ej.base.Ajax({

url: “/Home/ValidateEmployee”,

type: “POST”,

contentType: ‘application/json; charset=utf-8’,

data: JSON.stringify(e.data),

success: function (data) {

if (data.isValid) {

grid.saveChanges(); // Proceed with saving changes

} else {

// Handle validation errors

for (var key in data.errors) {

grid.addRecordError(data.errors[key], key);

}

}

}

});

ajax.send();

}

}

2. Server-Side Validation Method:

csharp

[HttpPost]

public JsonResult ValidateEmployee(Employee employee) {

var errors = new Dictionary<string, string>();

if (string.IsNullOrEmpty(employee.EmpFirstName)) {

errors.Add(“EmpFirstName”, “First Name is required.”);

}

// Add more validation checks as needed

return Json(new { isValid = !errors.Any(), errors });

}

For DevExpress Grid

  1. Enable Server-Side Validation: Use the ShowModelErrorsForEditors property in your GridView settings.

csharp

settings.SettingsEditing.ShowModelErrorsForEditors = true;

2. Handle Validation in the Controller:

csharp

public ActionResult Editing(Employee employee) {

if (ModelState.IsValid) {

// Save changes to the database

return Json(new { success = true });

}

// Return validation errors

return Json(new { success = false, errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage) });

}

For Telerik Grid

  1. Handle the Error Event: Prevent the popup from closing and display server validation errors.

javascript

function onError(e) {

var errors = e.errors;

if (errors) {

var grid = $(“grid”).data(“kendoGrid”);

grid.one(“dataBinding”, function (e) {

e.preventDefault();

$.each(errors, function (key, value) {

grid.editable.element.find(“[data-valmsg-for='” + key + “‘]”).replaceWith(‘<div class=”k-widget k-tooltip k-tooltip-validation”>’ + value + ‘</div>’).show();

});

});

}

}

Step 4: Display Validation Messages in the Grid

Ensure the GridView is set up to display validation messages. For instance, in the Syncfusion Grid, you can configure it to show errors next to the relevant fields by setting the ShowModelErrorsForEditors property.

Conclusion

You can successfully enable server-side validation for a GridView in your ASP.NET MVC application by following these instructions. By ensuring that user inputs are checked on the server, this method offers a reliable way to preserve data integrity while improving user experience.

Leave a Comment

Your email address will not be published. Required fields are marked *