简体   繁体   English

使用vb.net mvc中的knockout.js进行验证/远程验证

[英]Validation / Remote Validation with knockout.js in vb.net mvc

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. 我以为我可以使用远程验证,但该页面使用knockout.js,因此viewmodel是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. 从我收集的内容中,我必须在我的模型中传递,该模型在VB中具有数据注释以使用远程验证。 I can't seem to find examples of this feature that include the html so it's hard to figure out. 我似乎无法找到包含html的此功能的示例,因此很难弄清楚。

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. 它似乎应该有一个比jquery onchange事件更好的东西,并使用AJAX来调用我的控制器上的函数。

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. 我想我最终必须在控制器上调用我的函数来检查数据库,它更多的是jquery / html属性,我可以用尽可能干净的方式做到这一点,我正在努力。 Thanks for any advice. 谢谢你的建议。

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. 您可以在viewmodel上订阅用户名observable的更改,并向将返回bool的控制器发出ajax请求。

Something like this 像这样的东西

1) Your view model 1)您的视图模型

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 2)你的观点

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

3) Your controller 3)你的控制器

public class Registration : Controller 
{
   [HttpPost]
   public ActionResult IsUsernameUniqueue(string username)
   {
     // make a check here and return true or false...
     return Json(/*true or false*/);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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