繁体   English   中英

使用AJAX DOJO工具包检查ASP.Net中的用户名可用性

[英]Check Username Availability in ASP.Net using AJAX DOJO Toolkit

我目前正在尝试使用DOJO Toolkit开发一个小型演示,以便在ASP.NET中编写AJAX来检查用户名的可用性。

这是我的RegisterPage.aspx:

 <script type="text/javascript" src="jscripts/dojo/dojo.js" djconfig="parseOnLoad:true, isDebug:true"></script> <script type="text/javascript"> dojo.require('dojo.parser'); dojo.require("dijit.form.DateTextBox"); dojo.require("dijit.form.NumberSpinner"); dojo.require("dijit.form.Form"); dojo.require("dijit.form.Button"); dojo.require("dojox.validate"); dojo.require("dijit.form.ValidationTextBox"); dojo.require("dojox.validate.web"); dojo.require("dojox.form.PasswordValidator"); // To use AJAX dojo.require("dojo._base.xhr"); </script> <script type="text/javascript"> // When the DOM is ready.... dojo.ready(function () { // Local var representing the node to be updated var availabilityNode = dojo.byId("availabilityNode"); var usernameNode = dojo.byId("accountName"); // Connect button dojo.connect(usernameNode, "onkeyup", function () { // Get the value var value = dojo.trim(usernameNode.value.toLowerCase()); // If there's code... if (value != "") { // Using dojo.xhrGet, as very little information is being sent dojo.xhrPost({ // The URL of the request url: "./RegisterPage.aspx/checkUserName", // Allow only 2 seconds for username check timeout: 2000, // Send the username to check base on an INPUT node's value content: { userName: value }, handleAs: "text", // The success callback with result from server load: function (result, args) { if (result == "false") { availabilityNode.style.color = "green"; availabilityNode.innerHTML = "Username available!"; } else { availabilityNode.style.color = "red"; availabilityNode.innerHTML = "Username taken! Please try another."; } } }); } else { availabilityNode.innerHTML = ""; } }); }); </script> 
 <body class="tundra"> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"> <Scripts> <asp:ScriptReference Path="jscripts/AjaxDojoPatch.js" /> </Scripts> </asp:ScriptManager> <script type="dojo/method" event="onSubmit"> if (this.validate()){ return confirm("Form is valid, press OK to submit"); }else{ alert('Form contains invalid data. Please correct first'); return false; } return true; </script> <h1>DEMO REGISTER PAGE</h1> <table width="80%"> <tr> <td>Account Name*:</td> <td> <asp:TextBox ID="accountName" name="accountName" dojoType="dijit.form.ValidationTextBox" required="true" missingMessage="Ooops! You forgot your account name!" runat="server"></asp:TextBox></td> <td> <asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional"> <ContentTemplate> <!-- <asp:Button ID="btnCheckExist" runat="server" dojoType="dijit.form.Button" type="button" CausesValidation="false" label="Check Exist" Text="Check Exist" /> --> <asp:Label ID="lbl_check" runat="server" Text=""></asp:Label> <span id="availabilityNode"></span> </ContentTemplate> </asp:UpdatePanel> </td> </tr> <tr> <td>Password*:</td> <td colspan="2"> <asp:TextBox ID="pwd1" TextMode="Password" dojoType="dijit.form.ValidationTextBox" required="true" type="password" runat="server"></asp:TextBox> </td> </tr> <tr> <td>E-mail*:</td> <td colspan="2"> <asp:TextBox ID="email" required="true" dojoType="dijit.form.ValidationTextBox" runat="server" data-dojo-props="validator:dojox.validate.isEmailAddress, invalidMessage:'This is not a valid email!'"></asp:TextBox> </td> </tr> <tr> <td>Date of Birth:</td> <td colspan="2"> <asp:TextBox ID="birthDate" runat="server" dojoType="dijit.form.DateTextBox" value="7/5/1983"></asp:TextBox></td> </tr> <tr> <td></td> <td colspan="2"> <asp:Button ID="btnSubmit" dojoType="dijit.form.Button" type="submit" runat="server" label="Submit" Text="Submit" /> </td> </tr> </table> <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1"> <ProgressTemplate> Loading... please wait </ProgressTemplate> </asp:UpdateProgress> </form> </body> 

还有我的代码背后(RegisterPage.aspx.cs):

[System.Web.Services.WebMethod]
public static string checkUserName(string userName)
{
    string connectionString = ConfigurationManager.ConnectionStrings["connMain"].ConnectionString;
    SqlConnection currentConnection = new SqlConnection(connectionString);

    // System.Threading.Thread.Sleep(2000);
    string returnValue = string.Empty;
    try
    {
        // Create the command that will contain the SQL statement.
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "SELECT * FROM tbl_account WHERE accountName = '" + userName + "'";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = currentConnection;

        currentConnection.Open();

        if (userName.Length == 0)
        {
            returnValue = "false";
        }
        else
        {
            returnValue = Convert.ToString(cmd.ExecuteScalar());
        }

        return returnValue;
    }
    catch (Exception ex)
    {
        return returnValue;
    }
    finally
    {
        currentConnection.Close();
    }
}

当我尝试输入“用户名”文本框时,总是得到相同的结果:“已使用用户名!请尝试另一个。” 请帮助我解决此问题。 谢谢。

首先,您应该using连接和命令对象。 它们实现IDisposable ,这意味着它们有资源可以释放,而您没有释放它们。


第二,使用参数化查询 您现在对SQL注入非常开放。


第三,没有理由设置CommandType 默认为Text


问题似乎出在您的代码隐藏逻辑中。 问题是您检查了userName.Length ,但您从未将userName更改为除用户输入以外的任何内容。 因此,只要用户未输入空白名称,它的长度就总是大于0。 最具体地说,本节:

  SqlCommand cmd = new SqlCommand(); cmd.CommandText = "SELECT * FROM tbl_account WHERE accountName = '" + userName + "'"; cmd.CommandType = CommandType.Text; cmd.Connection = currentConnection; currentConnection.Open(); if (userName.Length == 0) { returnValue = "false"; } else { returnValue = Convert.ToString(cmd.ExecuteScalar()); } return returnValue; 

执行以下操作可以解决您的问题:

using (var cmd = new SqlCommand())
{
    cmd.CommandText = "SELECT * FROM tbl_account WHERE accountName = @Username";
    cmd.Connection = currentConnection;

    cmd.Parameters.AddWithValue("@Username", userName);

    using (var reader = cmd.ExecuteReader())
    {
        if (reader.HasRows)
        {
            returnValue = "false";
        }
        else
        {
            reader.Read();
            returnValue = reader["accountName"];
        }

        return returnValue;
    }
}

这应该向您展示如何进行我提到的所有更改,并解决您的问题。

暂无
暂无

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

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