在asp.net中使用页面方法时无法清除文本框

时间:2013-06-11 18:45:44

标签: javascript asp.net .net pagemethods

我一直在与.net PageMethods斗争。我有一个文本框,如果从数据库调用返回的值无效或者不在表中,我想清除它,现在有一个javascript显示弹出消息,但无法清除该字段。这是我的代码。

aspx code:
      asp:TextBox name="LoanNumber" ID="LoanNumber" runat="server" size="18" 
     style="font-size: 9pt"       ValidationGroup="requiredCheck" 
     onchange="javascript:SetFocus();loanCheckup();resetOnChange();" MaxLength="10" 
    ToolTip="Enter a Loan Number"  AutoPostBack="false"></asp:TextBox>

  <asp:RequiredFieldValidator   ID="reqLoanNumExists" runat="server"          ControlToValidate="LoanNumber" Display="Dynamic" 
    ErrorMessage="Required Loan Number"
     SetFocusOnError="true" ValidationGroup="requiredCheck">Required!     </asp:RequiredFieldValidator>
    <asp:RegularExpressionValidator ID="reqLoanNumber"
 ControlToValidate="LoanNumber" ValidationExpression="\d+"    Display="Static"             
   EnableClientScript="true"    SetFocusOnError="true" 
          ErrorMessage="Accepts Numbers Only!"    runat="server">
       </asp:RegularExpressionValidator>

页面方法(代码隐藏)   [的WebMethod]
     public static string getRowValue(string loanNum)       {

    string result = "";
    string tmpResultPass = "";
    string tmpResultFail = "";
 // doing all db connections here 
     try
        {
            if (cmdGetLoanNum.Connection.State == ConnectionState.Closed)
            {
                cmdGetLoanNum.Connection.Open();
            }

            tmpResultPass = cmdGetLoanNum.ExecuteScalar().ToString();

            tmpResultPass = tmpResultPass + "Is Valid";
            return   tmpResultPass ;

        }
        catch (Exception ex)
        {
            string msg = ex.StackTrace.ToString();
             tmpResultFail=  loanNum + " The Existing Loan Number entered does not    appear to be an active loan number.  Please confirm that the value was entered correctly! ";
         return tmpResultFail;


        }
        finally
        {
            cmdGetLoanNum.Connection.Close();
            cmdGetLoanNum.Dispose();
            myConnection.Dispose();
        }

我的java脚本:

    function loanCheckup() {

 // var txtLoanNum = document.getElementById('<%=LoanNumber.ClientID %>').value;

 var txtLoanNum = document.getElementById('LoanNumber').value;
//return Regex.IsMatch(txtLoanNum, "^-?\d*[0-9]?(|.\d*[0-9]|,\d*[0-9])?$");
  PageMethods.getRowValue(txtLoanNum, successLoan,failLoan);


}


 function successLoan(tmpResultPass) {

  alert(tmpResultPass);
 }


 function failLoan(tmpResultFail ) {

  alert(tmpResultFail);
 document.getElementById('LoanNumber').value = "";    
  }

现在当捕获到异常时,将出现tmpResultFail,但清除文本字段的下一行永远不会被执行。我有脚本管理器,启用pagemethods = true。除清除文本框字段外,一切正常。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

由于客户端控件与服务器端控件的ID不同,因此取消注释肯定无法正常工作。如果您查看页面源代码,则您的文本框不再被称为“LoanNumber”,因此.getElementById()将无效。

解决方案是:

  1. 使用控件的ClientID属性,就像在javascript评论中一样。

  2. 使用ASP.NET 4 ClientMode =“Static”来获得可预测的客户端ID。