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

Calling C# method using JQuery client side

4.59/5 (20 votes)
7 Sep 2011CPOL2 min read 181.2K  
This will help us to call method defined code behind using JQuery on Client Side

Introduction

This article helps us when we define a method code behind and want to call that method from client side. JQuery has made life simple. There is a very easy way to do that.

Background

Earlier we knew one way that we needed to add our method as a webmethod, if we want to call a method from code behind at client side. Using this, we can do it without calling our method in webmethod. We cannot call server-side code ‘directly’ from client-side code. Reason is by design, the server side code executes at server side and client side code at the client. However there are some workarounds.

Using the Code

In this example, I am writing a method to delete a particular user when a delete key is hit. I don't want a postback so I want the event to execute client side. I am writing a delete method server side in the CS file and calling it from client side using JQuery.

Create a page with name Text.aspx. Now open its CS file, that is Test.aspx.cs file and add a private method to delete a record. In this method, ID and UserId parameters are coming from client side. So you can learn how to get the parameters from client side.

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 clide side
            int UserID = Request.Form["UserID "].ToString().ToInteger();//parameter 
							//send from clide side
	    UserBO lObjUserBO = new UserBO ();
            lObjUserBO .DeleteUser(ID, UserID );
        }

Once we have defined the method, we need to call the client side method on page load. To call client side method on page load, we use Request.Form["MethodName"] == "Name of the method onclient side".

Here DeleteR is the name of the method on the client side and this method calls my private method defined on server side.

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

Now coming to the client side. We have an anchor tag and what we are looking at is when we click on this anchor tag, the method written on the server side should be called and a record with parameters passed from client side should be deleted.

C#
<a id="adelete">Delete </a>

Use the following script to call the server side method when this anchor tag is clicked. Here the name of my method is DeleteR which is called at page load server side. I am sending two parameters in this method, ID and UserID.

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 sucess will redirect to new page
                               
                            }
                        }
                        $.ajax(options);
               });

If the code executes successfully, it will redirect to a new page named Test1.aspx. We can even add what to do on Failure also.

Points of Interest

My client didn't want to see page refresh after delete. I had already created so many methods, I was just searching for a way to use the same method but from client side. This really helped me. Hope it helps you too.

License

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