Pregunta

Pretty simple goal, I want to make sure a username entered by a user is unique right after they enter it.

I thought I could use Remote Validation, but the page uses knockout.js so the viewmodel is JavaScript. From what I gather I would have to have passed in my model that has the data annotations in VB to use Remote Validation. I can't seem to find examples of this feature that include the html so it's hard to figure out.

How can I accomplish something similar with knockout? I've seen another knockout validation library but don't want to have to add another library to the solution unless it's the only option. It also seems like there should be something better than having an jquery onchange event and using AJAX to call a function on my controller.

I think I have to ultimately call my function on the controller to check the database, it's more the jquery/html attributes I can use to do this as cleanly as possible that I'm struggling with. Thanks for any advice.

¿Fue útil?

Solución

You can subscribe to the change of the username observable on your viewmodel and issue ajax request to the controller that will return the bool.

Something like this

1) Your view model

function registrationViewModel() {
   var self = this;
   self.username = ko.observable();
   self.usernameUniqueue = ko.observable(true);
   self.username.subscribe (function() {
    $.ajax({
        url: '/registration/isusernameuniqueue',
        data: { username: self.userName() },
        type: 'POST',
        success: function(result) {
          self.usernameUniqueue(result);
        }
    });
   });
}

ko.applyBindings(new registrationViewModel())

2) Your view

   <input type="text" data-bind="value: username" />
    <span data-bind="visible: !usernameUniqueue()" style="display:none">user name not uniqueue</span>

3) Your controller

public class Registration : Controller 
{
   [HttpPost]
   public ActionResult IsUsernameUniqueue(string username)
   {
     // make a check here and return true or false...
     return Json(/*true or false*/);
   }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top