Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

...where "GetPart" is the function name. However, this is not working. Please help me on this.

like image 606
charu Avatar asked Mar 03 '15 08:03

charu


People also ask

How Call JavaScript function from code behind in MVC?

You can't call a Javascript function from the CodeBehind, because the CodeBehind file contains the code that executes server side on the web server. Javascript code executes in the web browser on the client side.

How do I call a JavaScript function with parameters from code behind C#?

In order to call the JavaScript function with parameter from Code Behind, one has to make use of the RegisterStartupScript method of the ClientScript class in ASP.Net using C# and VB.Net. The following HTML Markup consists of an ASP.Net Button and a Label control.


2 Answers

in JavaScript:

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

Server side control:

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

C#

    protected void btnSample_Click(object sender, EventArgs e)
    {

    }

It is easy way though...

like image 200
Nachiket Avatar answered Oct 26 '22 15:10

Nachiket


You can do this by an 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 behind

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

or you can add a hidden button inside updatePanel, and invoke the click event using js. ('#<%=ID.ClientID%>').click(); It will invoke the OnClientClick if it exists then your codeBehind fucntion.

like image 37
Med.Amine.Touil Avatar answered Oct 26 '22 15:10

Med.Amine.Touil