ASP.NET Core 2.0 MVC [Remote] Validation






1.80/5 (2 votes)
How to implement model validation using [Remote] attribute in ASP.NET Core MVC. Continue reading...
Problem
How to implement model validation using [Remote]
attribute in ASP.NET Core MVC.
Solution
In Startup
, configure middleware and services for MVC:
public void ConfigureServices(
IServiceCollection services)
{
services.AddMvc();
}
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
Add a model
:
public class EmployeeInputModel
{
[Required]
[Remote(action: "ValidateEmployeeNo", controller: "Home")]
public string EmployeeNo { get; set; }
}
Add a controller
:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(EmployeeInputModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var json = JsonConvert.SerializeObject(model);
return Content(json);
}
public IActionResult ValidateEmployeeNo(string employeeNo)
{
if (employeeNo == "007")
return Json(data: "007 is already assigned to James Bond!");
return Json(data: true);
}
}
Add a razor page and scripts for jQuery and its validation:
using Fiver.Mvc.ModelValidation.Remote.Models.Home
@model EmployeeInputModel
<h2>ASP.NET Core MVC Client Validation</h2>
<form asp-controller="Home" asp-action="Index" method="post">
<div asp-validation-summary="All"></div>
<label asp-for="EmployeeNo"></label>
<input asp-for="EmployeeNo" />
<span asp-validation-for="EmployeeNo"></span>
<button type="submit">Save</button>
</form>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/
jquery.validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/
jquery.validate.unobtrusive.min.js"></script>
Discussion
ASP.NET Core MVC gives a useful [Remote]
attribute to make AJAX calls to controller/action to perform server-side validation, without the full post-back. The attribute uses jQuery and its validation JavaScript files to perform the AJAX requests.
We simply annotate the model
property with [Remote]
attribute, specifying Controller
and Action
. The action
itself returns a JSON result with either validation message or true
.