2014-11-02 42 views
0

我有一個用戶註冊頁面,我想檢查輸入的用戶名不是已經在用戶沒有回發。Javascript更新ASP:標籤不更新文本

ASPX頁面:

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
    <title></title> 
    <script src="Scripts/Registration.js" type="text/javascript"></script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager> 

    <table class="contenttable"> 
     <tr> 
      <td class="RegTableLabelCol"> 
       <asp:Label ID="Label1" runat="server" Text="User Name"></asp:Label> 
      </td> 
      <td class="RegTableDataCol"> 
       <asp:TextBox ID="txtUserName" runat="server" ></asp:TextBox> 
      </td> 
      <td class="RegTableMessageCol"> 
       <asp:Label ID="lblUserName" runat="server" CssClass="ErrorLabel" Text="Test "></asp:Label> 
      </td> 
     </tr> 
    </table> 
</form> 
    </body> 
</html> 

的JavaScript:

function UserChecker(username) { 

lbl = document.getElementById('<%=lblUserName.ClientID%>'); 

if (username != '') { 
    PageMethods.UserNameChecker(username, OnUserSucceeded); 
} 
else { 
    lbl.innerHTML = 'Please enter a username'; 
} 
} 

function OnUserSucceeded(result, userContext, methodName) { 

lbl = document.getElementById('<%=lblUserName.ClientID%>'); 

if (methodName == "UserNameChecker") { 

    if (result == true) { 
     lbl.innerHTML = 'User name not available'; 
    } 

    else { 
     lbl.innerHTML = 'User name is available '; 
    } 


} 

代碼背後:

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      txtUserName.Attributes.Add("onblur", "UserChecker(this.value)"); 
     } 
    } 
    [WebMethod] 
    public static bool UserNameChecker(string UserName) 
    { 
     string UserNameDb = null; 
     SQLMethods sqlm = new SQLMethods(); 

     DataSet dataSet1 = sqlm.IsUserNameExist(UserName); 

     foreach (DataRow row in dataSet1.Tables["UserName"].Rows) 
     { 
      UserNameDb = string.Format("{0}", row["UserName"]); 
     } 

     if (UserNameDb != null) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 

    } 

我已經把警報在JavaScript和功能似乎被解僱。麻煩的是標籤沒有被設置爲這兩種情況下(沒有用戶名,用戶名或用戶名確定)。我哪裏錯了?

UPDATE

的JavaScript是在.js文件中,如果我把它放在aspx頁面就拿起標籤和作品。

+0

甲側前端控制的ID:不使用'ScriptManager'只是沒有。 – 2014-11-02 17:38:39

+0

@RoyiNamir另類? – Fred 2014-11-02 17:47:41

+0

如果您在控制檯中遇到任何'JS'錯誤,請將其發佈! – 2014-11-02 17:54:31

回答

1
lbl = document.getElementById('<%=lblUserName.ClientID%>'); 

在JS文件中將不起作用。 <%=%>表示aspx頁面的服務器代碼部分。如果你把它放在一個JS文件中,它只是一個字符串。

您可以將此部分留在頁面中並將lbl聲明爲在JS文件引用中起作用的全局變量。

或者,也可以切換控制,以靜態的的ClientIDMode,然後使用在JS文件