Click here to Skip to main content
Click here to Skip to main content

Calling C# method using JQuery client side

By , 7 Sep 2011
 

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.

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.

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.

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

$('#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)

About the Author

Anuja Pawar Indore
Technical Lead Diaspark
India India
Member
I have keen interest in learning new things, exploring more on a topic and being more versatile

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
AnswerCalling C# method using JQuery client sidememberocprasok7 Dec '12 - 4:00 
try this http://dotnetstock.com/technical/how-to-call-code-behind-method-from-jquery[^]
QuestionError after executing ajax callmemberBharath Kumar Y30 Oct '12 - 0:57 
Hi, while im using this code in my project im getting an error after ajax call. need help on this...   the error shown in firbug was "SyntaxError: JSON.parse: unexpected character"
AnswerRe: Error after executing ajax callmemberAnuja Pawar Indore30 Oct '12 - 2:33 
See when you are passing datatosend, u r missing something there
GeneralRe: Error after executing ajax callmemberBharath Kumar Y30 Oct '12 - 20:04 
Ya im sending datatosend as u mentioned... Also why u r sending query string "new Date().getTime()" in the url below   url: '<%=ResolveUrl("("~/Test.aspx")") %>?x=' + new Date().getTime()
GeneralRe: Error after executing ajax callmemberAnuja Pawar Indore30 Oct '12 - 20:15 
So that two request never have a clash, their is unique identifier time attached to it.
GeneralMy vote of 5memberNajeeb Shaikh13 Sep '12 - 20:05 
Great article!
GeneralRe: My vote of 5memberAnuja Pawar Indore13 Sep '12 - 21:02 
Thanks
GeneralMy vote of 1memberMarkgam20 Aug '12 - 6:48 
Your code doesn't work
GeneralRe: My vote of 1memberAnuja Pawar Indore20 Aug '12 - 19:00 
Let me know what error you are facing, as its working fine at mine end.
Generalthankmembersachin_kulkarni991 Aug '12 - 18:48 
Hey,   Thanks for such useful post.   it helped me lot....!!!!!!
GeneralRe: thankmemberAnuja Pawar Indore2 Aug '12 - 23:58 
My pleasure Sachin
GeneralMy vote of 5membermanoj kumar choubey16 Feb '12 - 0:25 
Nice
GeneralRe: My vote of 5memberAnuja Pawar Indore26 Jul '12 - 20:26 
Thanks Manoj
GeneralMy vote of 1memberDaniel Gidman7 Sep '11 - 10:11 
the better method in a webforms environment is to use a web service or other similar type of method. An ashx is also a good approach to this. Move your actual function that does work into a separate class and you can call it from anywhere. It becomes much simpler in MVC where you can just call...
GeneralRe: My vote of 1memberAnuja Pawar Indore7 Sep '11 - 20:07 
I agree there are many alternatives to do. But i feel this was easy and safe.
GeneralRe: My vote of 1membersingh.iz.king21 Dec '11 - 16:58 
OK, it was an easy way out, but seriously what is safe about this when compared to doing it properly (i.e. using a webservice or ashx handler)?
GeneralRe: My vote of 1memberAnuja Pawar Indore7 Sep '11 - 20:15 
Create a web service name WebMethod.SVC in the CS file add the method   [OperationContract] [WebInvoke(Method = "POST")] public void DeleteRec(string ID) { DelUser(Convert.ToInt32(ID)); }   On client side give the path and call the method...
GeneralMy vote of 5memberAnuja Pawar Indore7 Sep '11 - 3:35 
Helped me to call my method
GeneralRe: My vote of 5memberAnuja Pawar Indore12 Oct '11 - 23:12 
Thanks
GeneralRe: My vote of 5mvpSacha Barber15 Nov '11 - 23:34 
Are you having a conversation with yourself here? Sacha Barber Microsoft Visual C# MVP 2008-2011Codeproject MVP 2008-2011Open Source Projects Cinch SL/WPF MVVM Your best friend is you. I'm my best friend too. We share the same views, and hardly ever argue   My Blog : sachabarber.net
GeneralRe: My vote of 5memberAnuja Pawar Indore16 Nov '11 - 0:01 
Its good to have self conversation but in this case was a mistake as my first time

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 7 Sep 2011
Article Copyright 2011 by Anuja Pawar Indore
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid