在vb.net MVC中使用Knockout.js进行验证/远程验证 [英] Validation / Remote Validation with knockout.js in vb.net mvc

查看:71
本文介绍了在vb.net MVC中使用Knockout.js进行验证/远程验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常简单的目标,我想确保用户输入的用户名在输入后立即是唯一的.

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

我以为我可以使用远程验证,但是页面上使用了基因敲除.js,因此视图模型是JavaScript.从我收集的数据来看,我必须传递我的模型,该模型在VB中具有数据注释才能使用远程验证.我似乎找不到包含html的此功能的示例,因此很难弄清楚.

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.

我如何通过淘汰赛完成类似的任务?我已经看到了另一个敲除验证库,但是除非它是唯一的选择,否则不想将其添加到解决方案中.似乎还应该有一个比jquery onchange事件和使用AJAX在我的控制器上调用一个函数更好的东西.

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/html属性,以使其尽可能地整洁地工作.感谢您的任何建议.

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.

推荐答案

您可以订阅在视图模型上可观察到的用户名更改,然后向将返回bool的控制器发出ajax请求.

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.

类似这样的东西

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)您的看法

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

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

这篇关于在vb.net MVC中使用Knockout.js进行验证/远程验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆