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.

Answers:

Answer

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...

Answer

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.

Answer

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

                    }
                });
});

});
Answer

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

        }
    });
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.