Welcome to our comprehensive guide on ASP .NET Remote Validation! This tutorial is designed for both beginners and intermediate learners, focusing on explaining the concept from the ground up. Let's dive in! 🤿
Remote Validation in ASP .NET allows you to validate form fields without relying on client-side JavaScript. It helps maintain consistency in data and improves overall user experience.
Microsoft.AspNetCore.Mvc.DataAnnotationsIn your Model, create a method annotated with [RemoteAttribute]. This method will be called when validation is required.
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.DataAnnotations;
public class User
{
[Remote("IsUserNameAvailable", "Home")]
public string UserName { get; set; }
}
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult IsUserNameAvailable(string userName)
{
// Your validation logic here
// Return JsonResult with true or false
}
}For Razor Pages, the process is slightly different. You'll need to create a custom validator and apply it to your OnGet and OnPost methods.
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Mvc.Validation;
public class CustomRemoteValidator : RemoteValidator
{
public CustomRemoteValidator(IValidatorFactory validatorFactory) : base(validatorFactory)
{
}
protected override void OnValidate(ValidateContext validateContext)
{
base.OnValidate(validateContext);
var model = validateContext.ModelMetadata;
if (model.IsComplexType)
{
foreach (var property in model.Properties)
{
OnValidate(validateContext.CreateValidateContext(property.ContainerInstance, property.ModelName, property.Model));
}
}
}
}Apply the custom validator to your Razor Page:
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Mvc.Validation;
public class IndexModel : PageModel
{
[CustomRemoteValidator]
public string UserName { get; set; }
public void OnGet()
{
}
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
return Page();
}
// Your logic here
return RedirectToPage("./Result");
}
}What does Remote Validation do in ASP .NET?
That's it for our Remote Validation tutorial! We hope you found this guide informative and helpful. Happy coding! 🤝🏼