0

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?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Don
  • 13
  • 3
  • Where are you trying to call this? Can you show your javascript code as well? – pquest Jan 04 '22 at 22:57
  • @pquest I haven't made changes in the js code for that. Do I have to? I didn't find anything for it, can you explain me what I have to do? – Don Jan 04 '22 at 23:01
  • I have never used this, but reading the docs you linked, this remote feature seems to tie in to the Jquery remote validation feature. https://jqueryvalidation.org/remote-method/ – pquest Jan 05 '22 at 13:11

1 Answers1

0

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:

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
G. Belkin
  • 56
  • 3
  • No, it doesn't have the [ApiController] attribute, in the tutorials / posts I searched no one mentioned it for remote validation. I added it, but now I'm getting errors, currently working on them. – Don Jan 05 '22 at 14:38