0

I'm currently trying to develop a small demo using DOJO Toolkit to write an AJAX in ASP.NET to check for username availability.

This is my 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>

And my Code Behind (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();
    }
}

When i tried to type in Username Textbox, it's always get the same result: "Username taken! Please try another." Please help me fix this issue. Thanks.

1
  • I recommend that when you get this working, you head over to Code Review and get some feedback on what can be done better in your code. Commented Nov 15, 2015 at 15:46

1 Answer 1

1

First, you should be using your connection and command objects. They implement IDisposable which means they have resources to free, and you don't free them.


Second, use parameterized queries. You are very open to SQL injection right now.


Third, there's no reason to set the CommandType. It defaults to Text.


The problem appears to be in your codebehind logic. The problem is that you check userName.Length, but you never change userName to anything except whatever the user input. So it's always going to have a length greater than 0 so long as the user didn't input a blank name. Most specifically, this section:

    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;

Doing the following should fix your issue:

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;
    }
}

This should show you how to make all the changes I mentioned, and fix your issue.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.