Using remote validation with ASP.NET Core

2020-02-12 10:16发布

问题:

I am trying to create a remote validation as follows:

[Remote("CheckValue", "Validate", ErrorMessage="Value is not valid")]
public string Value { get; set; }

I am using ASP.NET Core (ASP.NET 5) and it seems Remote is not available. Does anyone know how to do this with ASP.NET CORE?

回答1:

The RemoteAttribute is part of ASP.Net MVC Core:

  • If you are using RC1, it is in the Microsoft.AspNet.Mvc namespace. See RemoteAttribute in github.
  • After the renaming planned in RC2, it will be in the Microsoft.AspNetCore.Mvc namespace. See RemoteAttribute in github.

For example, in RC1 create a new MVC site with authentication. Then update the generated LoginViewModel with a dummy remote validation calling a method in the home controller:

using Microsoft.AspNet.Mvc;
using System.ComponentModel.DataAnnotations;
public class LoginViewModel
{
    [Required]
    [EmailAddress]
    [Remote("Foo", "Home", ErrorMessage = "Remote validation is working")]
    public string Email { get; set; }

    ...
}

If you create that dummy method in the home controller and set a breakpoint, you will see it is hit whenever you change the email in the login form:

public class HomeController : Controller
{

    ...

    public bool Foo()
    {
        return false;
    }
}


回答2:

In the meantime, the documentation is there and available here. In a nutshell you just need to decorate your view model's property with the following:

    [Remote(action: "Foo", controller: "Bar", ErrorMessage = "Remote validation is working")]
    [Required]        
    [Display(Name = "Name")]
    public string Name { get; set; }

Then create an action (named 'Foo' in this example) in the controller (named 'Bar' in this example) and add your logic there:

  [AcceptVerbs("Get", "Post")]
  public async Task<IActionResult> Foo(string name)
  {
      bool exists = await this.Service.Exists(name);
      if (exists)
          return Json(data: false);
      else
          return Json(data: true);
  }

Final note: the Remote attribute is in the Microsoft.AspNetCore.Mvc namespace.