简体   繁体   中英

ASP.NET core 3.1 [Remote] validation not working

Ok, before getting downvoted to oblivion I want to state that I honestly searched this topic for the past couple of days and although I've come across several posts / videos I can't get it to work properly.

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:

  1. I tried added jQuery scripts on my view / Layout page, nothing happens. Also, is that necessary?
  2. I installed the jQuery.Validation NuGet package.
  3. Right before the IsNameAvailable action I changed the [AcceptVerbs("Get", "Post")] to [HttpPost] . I also added [ValidateAntiForgeryToken] and some other things, but no luck.
  4. I changed the action from IActionResult IsNameAvailable to async Task<IActionResult> or JsonResult . (No idea what all of that means.)
  5. I was so desperate I even tried the controller: "ClientController" instead of controller: "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 ModelState directly.

if (!ModelState.IsValid)
{
    return BadRequest(ModelState);
}

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM