mysticalstick
mysticalstick

Reputation: 165

Embed C# code in JavaScript?

In my .aspx file I have a button

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

Normally in the .cs file if I needed to call any methods for the button I would call BtnSearch.method() but I have a function in the JavaScript for EditClick() and I would like to call BtnSearch.Enable = false but I get an exception. How would I disable this button in the JavaScript function?

Upvotes: 2

Views: 1391

Answers (2)

Win
Win

Reputation: 62300

You can use jQuery. These days, you won't normally see a website which doesn't use jQuery or Javascript Framework.

Since you cannot predict Server Control ID at run-time, you want to use #<%= 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>

I personally do not like using ClientIDMode="static", unless I do not have any other option.

Upvotes: 1

Jamadan
Jamadan

Reputation: 2313

You could use the

OnClientClick=""

attribute in the asp button?

Then run inline code similar to

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

Final view:

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

Upvotes: 1

Related Questions