'Using remote validation with ASP.NET Core

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?



Solution 1:[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;
    }
}

Solution 2:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel J.G.
Solution 2 hbulens