ASP.NET MVC用户名可用性检查 [英] ASP.NET MVC username availability check

查看:85
本文介绍了ASP.NET MVC用户名可用性检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了很多循序渐进的教程,但仍然无法使我的代码正常工作,我也很幸运地浏览了该站点上的解决方案,我也不知道我在做什么错.

I have read a lot of step by step tutorials and still couldn't get my code to work, I went through the solutions on this site with no luck either, i don't know what i am doing wrong.

我正在使用jQuery,想了解用户名"mark"是否被使用,我什至还没有达到数据库链接.

I am using jQuery and want to find out whether the username "mark" is taken or not, I haven't even reached the database linkage yet.

[HTML]

<input id="user_name" name="user_name" onchange="UserCheck()" type="text" value="" />
<div id="status" />

[JS]

function UserCheck() {
    $("#status").html("Checking....");
    $.post("/user/check",
    { username: $("#user_name").val() },
    function (data) {
        if (data == 0) {
            $("#status").html("Available");
        }
        else {
            $("#status").html("Taken");
        }
    });
}


[Controller]

public JsonResult check(FormCollection form)
{
    System.Threading.Thread.Sleep(3000);
    string name = form["username"];

    if (name.Equals("mark")){
        return Json(1);
    } else {
        return Json(0);
    }
}

推荐答案

检查以下链接:

立即检查用户名存在-ASP.NET MVC远程验证

这里您需要的是要检查的属性的RemoteAttribute,还需要实现一个控制器操作,该操作返回带有布尔值的JsonResult.

What you need here is RemoteAttribute for the property your are checking and also you need to implement a controller action which returns JsonResult with Boolean value.

这里是一个简短的示例:

Here is a brief sample:

您的型号:

    [Required]
    [Display(Name = "User name")]
    [Remote("doesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name already exists. Please enter a different user name.")]
    public string UserName { get; set; } 

您的操作结果:

[HttpPost]
public JsonResult doesUserNameExist(string UserName) {

    var user = Membership.GetUser(UserName);

    return Json(user == null);
}

您可以根据需要调整操作结果中的业务逻辑.

You can tweak the business logic inside the action result for your needs.

此外,请确保您在注册页面上引用了以下库以及 jQuery 文件:

Also, make sure that you have the following libraries referenced on your registration page along with your jQuery file:

jquery.validate.min.js

jquery.validate.min.js

jquery.validate.unobtrusive.min.js

jquery.validate.unobtrusive.min.js

以上博客文章涵盖了您所需的一切.

The above blog post covers everything you need.

注意

请记住,Remote验证不会在服务器端启动.您可能想检查下面的链接以进行服务器端远程验证(尽管我不建议在生产环境中使用它,因为它充满了漏洞,但是会给您一个想法):

Keep it in mind that Remote validation does not kick in on the server side. You might wanna check the below link out for server side remote validation (I don't recommend using it on production though, it is full of holes but it will give you an idea):

http://www.tugberkugurlu.com/存档/asp-net-mvc-server-side-remote-validation

这篇关于ASP.NET MVC用户名可用性检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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