Using remote validation with ASP.NET Core

前端 未结 2 1709
花落未央
花落未央 2020-12-19 07:38

I am trying to create a remote validation as follows:

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


        
相关标签:
2条回答
  • 2020-12-19 07:59

    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.

    0 讨论(0)
  • 2020-12-19 08:14

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题