How can I call the server side button click function?

I have a server side function

protected void SearchButton_Click(object sender, EventArgs e)       
{

}

I need to call the same client side script

function calSearch()
{
    // here I need to call the client side script
}
+4
source share
3 answers

You cannot do this, your option is to simulate a button click 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>

Another solution would be to use ajax.

+6
source

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>

WebMethod AJAX, asp- WebMethod.

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

, SearchButton,

function calSearch(){

__doPostBack('SearchButton','');

}

Note. Before doPostBack () function

There are two underscores:

Best way to do it here

0
source

Source: https://habr.com/ru/post/1532251/


All Articles