I'm coding in ASP.NET core 3.1 and I want to add the [Remote] attribute on my model. I looked at the official documentation page and coded something like that:
Code at my controller "ClientController":
[AcceptVerbs("GET", "POST")]
public IActionResult IsNameAvailable(string name) {
return Json(false);
}
Code at my model:
[Required(ErrorMessage = "Name is required")]
[StringLength(80, MinimumLength = 3, ErrorMessage = "Name length must be between 3 to 80 characters.")]
[Remote(action: "IsNameAvailable", controller: "Client", ErrorMessage = "It's working.")]
public string Name { get; set; }
But it's not working. To be exact, it seems that the action doesn't get triggered at all. I tried adding some breakpoints or throw errors inside the IsNameAvailable and nothing.
I searched a bit about remote validation and I really got confused, because everyone is doing something different and nothing works for me:
- I tried added jQuery scripts on my view / Layout page, nothing happens. Also, is that necessary?
- I installed the jQuery.Validation NuGet package.
- Right before the
IsNameAvailableaction I changed the[AcceptVerbs("Get", "Post")]to[HttpPost]. I also added[ValidateAntiForgeryToken]and some other things, but no luck. - I changed the action from
IActionResult IsNameAvailabletoasync Task<IActionResult>orJsonResult. (No idea what all of that means.) - I was so desperate I even tried the
controller: "ClientController"instead ofcontroller: "Client"but of course that wasn't the case.
What am I missing?
Does your controller have
[ApiController]attribute? This attribute enables the validation by default.Otherwise you may check your
ModelStatedirectly.If this doesn't help, you'll need to you show us the contoller's code, so we have more context to work off of.
Source: