How to call a codebehind function from javascript

2020-04-02 08:10发布

问题:

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.

回答1:

in JavaScript:

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

Server side control:

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

C#

    protected void btnSample_Click(object sender, EventArgs e)
    {

    }

It is easy way though...



回答2:

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.



回答3:

try this

Your code behind function

[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)
                    {

                    }
                });
});

});


回答4:

Using ajax, you can call a codebehind function from javascript using JQuery:

function : fnCheckSelection(){
    $.ajax({
        cache: false,
        url: "/GetPart"
        type: "POST",
        success: function (result) {

        },
        error: function (msg) {

        }
    });
}