简体   繁体   中英

Calling C# Method Using Javascript

I am trying to access a method in my code behind called "Button1_Click" using Javascript, I think there is something wrong in my code below because currently I have to click twice in order for the method to trigger, one click doesn't trigger the method.

My Test Code:

// Javascript

<script type="text/javascript">
 function CallMe() { document.getElementById('<%= ButtonHidden.ClientID %>').click(); }
</script>

// Markup

<asp:Button ID="ButtonVisible" runat="server" Text="Test Button"
  OnClientClick="CallMe();"/>
<asp:Button ID="Button1" runat="server" style="display:none;" Text="Click"
  OnClick="Button1_Click"/>

// Code Behind Method

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Redirect("http://google.com");
}

Am I missing something?

You could use the OnClientClick property of the Button:

<asp:button id="Button1"
   text="Test Button"
   onclientclick="CallMe()"
   runat="server" onclick="Button1_Click" />

Then you don't need another (hidden) button.

Your CallMe() method should then return either true (if everything is OK) or false (to cancel the postback).

Instead of using javascript why not simply assign the same server click handler for both buttons:

<asp:Button 
    ID="ButtonVisible" 
    runat="server" 
    Text="Test Button" 
    OnClick="Button1_Click" />

<asp:Button 
    ID="Button1" 
    runat="server" 
    style="display:none;" 
    Text="Click" 
    OnClick="Button1_Click" />

UPDATE:

A better solution would be to have your javascript function return a boolean value depending on whether some conditions are met which will execute the server handler:

<script type="text/javascript">
    function CallMe() {         
        if (some condition) {
            return true; // allow the server to be called
        }
        return false;
    }
</script>

and then use both OnClick and OnClientClick on the button:

<asp:Button 
    ID="ButtonVisible" 
    runat="server" 
    Text="Test Button" 
    OnClientClick="return CallMe();"
    OnClick="Button1_Click" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM