Validation / Remote Validation with knockout.js in vb.net mvc

依然范特西╮ 提交于 2019-12-25 01:14:33

问题


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.


回答1:


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*/);
   }
}


来源:https://stackoverflow.com/questions/23521427/validation-remote-validation-with-knockout-js-in-vb-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!