2015-11-15 76 views
1

我正在嘗試開發一個使用DOJO工具包在ASP.NET中編寫AJAX以檢查用戶名可用性的小型演示。使用AJAX查詢ASP.Net中的用戶可用性使用AJAX DOJO工具包

這是我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"> 
 
\t \t \t  if (this.validate()){ 
 
\t \t \t \t  return confirm("Form is valid, press OK to submit"); 
 
\t \t \t  }else{ 
 
\t \t \t \t  alert('Form contains invalid data. Please correct first'); 
 
\t \t \t \t  return false; 
 
\t \t \t  } 
 
\t \t \t  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(); 
    } 
} 

當我試圖在用戶名輸入文本框,它總是得到相同的結果:「用戶名,請嘗試其他。」 請幫我解決這個問題。謝謝。

+0

我建議**,當你得到這個工作**時,你會回到[CodeReview.SE]並獲得一些關於你的代碼中可以做得更好的反饋。 –

回答

1

首先,你應該是using你的連接和命令對象。他們實施IDisposable這意味着他們有資源可以免費,而且你不會釋放它們。


二,使用parameterized queries。你現在是開放SQL注入。


三,沒有理由設置CommandType。它defaults to 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; 
    } 
} 

這應該告訴你如何讓我提到的所有更改,並解決您的問題。

+0

對不起,夥計。沒有工作:( –