Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Calling a C# method using jQuery on the client side

4.76/5 (19 votes)
15 Sep 2011CPOL1 min read 99.7K  
Calling a C# method using jQuery on the client side.

This code will help you when you need to define a method code-behind and want to call that method from the client side. jQuery has made life simple. There is a very easy way to do this.


Earlier, we knew one way that we needed to add our method as a WebMethod if we wanted to call a method from the code-behind at the client side. Using this method, we can do it without calling our method in a WebMethod.


In this example, I am writing a method to delete a particular user when the Delete key is hit. I don't want a postback so I want the event to execute on the client side. I write a Delete method on the server side in the CS file and call it from the client side using jQuery. The name of my page is Test.aspx.


This is my method in the CS file with the name DeleteRec().


C#
private void DeleteRec()
{
    int ID= Request.Form["ID"].ToString().ToInteger(); 
    //parameter send from client side
    int UserID = Request.Form["UserID "].ToString().ToInteger();
    //parameter send from client side
    UserBO lObjUserBO = new UserBO ();
    lObjUserBO .DeleteUser(ID, UserID );
}

Here is how we call the method on page load:


C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        #region Ajax methods
        if (Request.Form["MethodName"] == "DeleteR")
        // same Method Name that we are specifying on client side(DeleteR)
        {
            DeleteRec();// Method defined on the page to delete the record
            return;
        }
        #endregion
    }
}

This is what we need to add at the client side (Test.aspx).


HTML
<a id="adelete" href="java<!-- no -->script:void(0);">Delete</a>

Use the following script to call the server side method when this anchor tag is clicked:


JavaScript
$('#adelete').click(function()
{
    var dataToSend={ID:ID,MethodName:'DeleteR',UserID :UserID };

    var options =
    {
        url: '<%=ResolveUrl("~/Test.aspx") %>?x=' + new Date().getTime(),
        data: dataToSend,
        dataType: 'JSON',
        type: 'POST',
        success: function (response) {
        window.location.href='<%=ResolveUrl("~/Test1.aspx")%>/'+ID;
        //after success will redirect to new page
    }
}
$.ajax(options);
});

Hope you find it useful, when trying to call a server side method client side.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)