2016-06-14 42 views
2

在我.aspx文件我在.cs文件按鈕在JavaScript中嵌入C#代碼?

<asp:Button ID="BtnSearch" runat="server" Text="Search" ValidationGroup="SearchRoles" CausesValidation="true" OnClick="BtnSearch_Click" /> 

通常情況下,如果我需要調用的按鈕任何方法我會打電話BtnSearch.method()但我在JavaScript中的函數EditClick(),我想撥打BtnSearch.Enable = false但我收到一個例外。如何禁用JavaScript功能中的此按鈕?

回答

1

您可以使用jQuery。現在,你通常不會看到一個不使用jQuery或Javascript框架的網站。

由於您無法在運行時預測服務器控件ID,因此您希望使用#<%= SearchButton.ClientID %>

enter image description here

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
<asp:Button ID="SearchButton" runat="server" Text="Search" 
    ValidationGroup="SearchRoles" CausesValidation="true" 
    OnClick="SearchButton_Click" /> 
<br /> 
<input type="checkbox" id="DisableButtonCheckBox" /> 
    Check to disable button 
<script type="text/javascript"> 
    $(function() { 
     $("#DisableButtonCheckBox").click(function() { 
      if (this.checked) { 
       $("#<%= SearchButton.ClientID %>").prop("disabled", true); 
      } else { 
       $("#<%= SearchButton.ClientID %>").prop("disabled", false); 
      } 
     }); 
    }); 
</script> 

我個人不喜歡使用ClientIDMode="static",除非我沒有任何其他選擇。

1

你可以使用在ASP按鈕

OnClientClick="" 

屬性?

然後運行類似於

$(this).prop('disabled', true); 

最後查看內嵌代碼:

<asp:Button ID="BtnSearch" runat="server" Text="Search" ValidationGroup="SearchRoles" CausesValidation="true" OnClick="BtnSearch_Click" OnClientClick="$(this).prop('disabled', true);"/>