How to call codebehind function from javascript in asp.net?

I want to call a function from my code using javascript. I used the code below:

function fnCheckSelection() { some script; window["My"]["Namespace"]["GetPart"](null); } 

... where "GetPart" is the name of the function. However, this does not work. Please help me with this.

+6
source share
4 answers

in javascript:

  document.getElementById("btnSample").click(); 

Server side management:

  <asp:Button runat="server" ID="btnSample" Text="" style="display:none;" OnClick="btnSample_Click" /> 

WITH#

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

It's easy though ...

+12
source

You can do this with ajax call

this is a jquery example:

 $.ajax({ type: "POST", url:"~/code_behind.aspx/Method", data: dataPost, contentType: "application/json; charset=utf-8", dataType: "json", .... }); 

here is api documentation and in code

 [WebMethod] public static yourType Method (Params){} 

or you can add a hidden button inside updatePanel and trigger the click event with js. ('#<%=ID.ClientID%>').click(); It will call OnClientClick, if it exists, then you use the codeBehind function.

+4
source

try it

Function of your code for

 [WebMethod] public static void GetPart() { //your code goes here } 

. Javascript

 $(document).ready(function () { $("#btnname").click(function () { $.ajax({ type: "POST", url: "/youraspxpagename.aspx/GetPart", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { } }); }); }); 
+1
source

Using ajax, you can call the codebehind function from javascript using jQuery:

 function : fnCheckSelection(){ $.ajax({ cache: false, url: "/GetPart" type: "POST", success: function (result) { }, error: function (msg) { } }); } 
-1
source

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


All Articles