使用ajax和asp.net验证用户标识和密码

时间:2009-11-11 11:30:08

标签: jquery asp.net ajax

我想知道如何使用ajax和jquery在asp.net应用程序中对userId和password进行验证,因为我是ajax的新手 任何帮助都将得到高度关注

3 个答案:

答案 0 :(得分:0)

首先是服务器端脚本需要useridpassword个参数并验证它们是否有效。

将Check.ashx通用处理程序添加到您的项目中:

<%@ WebHandler Language="C#" Class="Check" %>

using System.Web;

public class Check : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        var userid = context.Request["userid"];
        var password = context.Request["password"];

        string response = IsValid(userid, password) ? "true" : "false";
        context.Response.ContentType = "appliaction/json";
        context.Response.Write("{isvalid:'" + response + "'}");
    }

    private bool IsValid(string userid, string password)
    {
        return (userid == "john" && password == "secret");
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

然后让您的页面发送ajax查询。

Default.aspx的:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $('a.check').click(function() {
                $.ajax({
                    url: '/check.ashx',
                    dataType: 'json',
                    data: {
                        userid: $('input[name=userid]').val(),
                        password: $('input[name=password]').val()
                    },
                    success: function(json) {
                        alert(json.isvalid);
                    }
                });
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        userid: <input type="text" name="userid" value="" />
        password: <input type="text" name="password" value="" />
        <a href="#" class="check">Check</a>
    </div>
    </form>
</body>
</html>

答案 1 :(得分:0)

好吧,ajax基本上是从客户端调用webservices / wcf的能力(javascript),你用参数执行一些webmethod,并接收一些数据,这样就可以了。

你也不应该只依靠客户端验证,因为用户只能从他的浏览器中禁用javascript并且所有的ajax东西/ javascript都无法正常工作

答案 2 :(得分:0)

有趣的是你应该问,我昨晚开始发布这篇博文,没有开玩笑!!!

http://professionalaspnet.com/archive/2009/11/11/Validating-A-Username-Using-JQuery-and-ASP.NET-Membership-Provider.aspx