Using remote validation with ASP.NET Core

大兔子大兔子 提交于 2019-12-01 03:58:29

问题


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.



来源:https://stackoverflow.com/questions/36033022/using-remote-validation-with-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!