How can i call a server side button click function from client side?

28,160

Solution 1

You cant do this, your option is to simulate Click of a button using javascript.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

HTML markup will look like this:

<button id="btnsave" onclick="fncsave()">Save</button>

now simulate a Click using JS

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

Other solution would be to use ajax.

Solution 2

you can use __doPostBack method

function functionName()
{

__doPostBack('ButtonId','OnClick');

}

or you can try this....

<button id="btnsave" onclick="callfunction()">Save</button>// to all javascript
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" style="display:none" />


<script type="text/javascript">
     function callfunction()
     {  
         /*do your javascript coding here*/
        document.getElementById('<%= btnSave.ClientID %>').click();
       // we are firing onClick event for  asp button btnsave form javascript.
     }
</script>

otherwise you can create WebMethod in code behind and make AJAX call but then you wont be able to access asp control in WebMethod.

   $.ajax({
            type: "POST",
            url: "AspDotNetPage{}'{"+myData+"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
               alert(msg);                
            }
          });
Share:
28,160
Kailas
Author by

Kailas

Updated on April 13, 2020

Comments

  • Kailas
    Kailas about 4 years

    I have a server side function

    protected void SearchButton_Click(object sender, EventArgs e)       
    {
    
    }
    

    I need to call the same from a client side script

    function calSearch()
    {
        // here I need to call the client side script
    }
    
  • Pierre
    Pierre about 9 years
    This works best and is the shortest way of going about server-side click, Thanks :) i.imgur.com/XxvWwO6.png