Click here to Skip to main content
15,887,379 members
Articles / Programming Languages / C# 5.0
Tip/Trick

How to Call Code Behind Method from Client Side

Rate me:
Please Sign up or sign in to vote.
4.94/5 (12 votes)
20 Dec 2016CPOL2 min read 57.2K   24   7
Using JavaScript and jquery, I will demonstrate how to call codebehind method from the client side. There are three ways of doing so.

Introduction

The code snippet here will help data interaction from client side to the code behind methods helpful in lightweight web based applications.

Background

The implementer must have a basic idea of code behind methods, static methods and hands on expertise in JavaScript and jquery.

Using the Code

Here, we shall follow the camelCase naming terminology to name the methods both in JavaScript/jquery and code behind (C#).

The Uno Way

JavaScript
function getDataFromCodeBehind()
{
var result=PageMethods.getUserName(onSuccess,onError)
}
 
function onSuccess(data)
{
alert(data);
}

function onError(errorMessage)
{
alert(errorMessage);
}

In the HTML markup, you will need to add the following line of code:

ASP.NET
<asp:ScriptManager ID="ScriptManager1" runat="server" 
EnablePageMethods="true"></asp:ScriptManager>

and the code behind method (CallingCodeBehindMethod.aspx) would look like this:

C#
[WebMethod] // using System.Web.Services;

public static string getUserName()
{
return "Mr. Shivi Gupta from Lucknow";
}

The Second Way

Now let us do that using $.ajax method which makes use of a XMLHttpRequest to get the data.

The code snippet for the jquery method is:

JavaScript
$.ajax({
type: "POST",
url: "CallingCodeBehindMethod.aspx/getUserName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) 
{
alert(msg.d);
}
});

You can read the documentation of $.ajax method here for more details.

And For the Hat trick, We Have To Use ajax.dll As:

JavaScript
function ajaxDllgetDataFromCodeBehind()
{
var result = ReporterClass.getUserNameFromAjaxDll();
alert(result.value);
}

And in addition to this, you will have to add ajax.dll as a reference in your solution. You can download it from here.

And also change the web config as:

XML
</connectionStrings>
<system.webServer>
<handlers>   
<add name="CallCodeBehind" verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>   
</handlers>
</system.webServer>

And one last thing to be added is a reporterClass.cs file with the method getUserNameFromAjaxDll() in it as:

C#
public class ReporterClass
{
[Ajax.AjaxMethod()]
public static string getUserNameFromAjaxDll()
{
return "Mr. Shivi Gupta from Lucknow";
}
}

And also to register the ReporterClass in your aspx page, we have to go to the page load method and type the following lines:

C#
if (!IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache); // to disable cache
Response.Cache.SetAllowResponseInBrowserHistory(false);
Ajax.Utility.RegisterTypeForAjax(typeof(ReporterClass));
}

I know the last way is a little too hectic, but it comes in handy when you have to use a MVVM model and use method overloading or fetching huge amounts of data.

So now I leave it up to you which method to use in which situation, the Page methods way is my personal best.

And as a bonus, there is one more way of achieving the probable.

The Hidden Way

We use the hidden fields to set the value in the code behind and then use it in the client side with the super power use of the setTimeout method to fetch the values which we needed so desirably from the server.

C#
public void setHiddenFieldData()
{
HF_Value1.Value=ds.Tables[0].Rows[0][0];
}

So the above code is in C#, where ds is the dataset fetched from the database.

And the client side looks like this:

C#
function getServerSideHiddenField()
{
var t = self.setTimeout(function()
{
var hf_FieldData=document.getElementById('HF_Value1').value;
},1000);
}

So we call both the client side and server side methods at page load and rely on the magic of setTimeout to get the value we want.

Points of Interest

The code behind method has to be static only then the client side will read it as an accessible web method as in only a static method in code behind.

History

  • First attempt!
  • Hidden field usage added

License

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


Written By
Software Developer
India India
Shivi is currently working as Software Engineer in Mumbai, India, gaining expertise in asp.net, c#,vb,swift,java,vb.net,SQL Server,MVC, Azure,Google Maps API,Angular,Resharper,Winforms,python, data science, AWS and also has proficiency in web designing, using html, css3 and javascript/jquery,mongodb and java.
Shivi has developed a heavy interest in AI and machine learning.
Shivi has an android app on the play store:
https://play.google.com/store/apps/details?id=hungrybaba.quoter
The same quoter app on the app store:
https://apps.apple.com/in/app/quotertwo/id1476920917

Apart from coding, Shivi covets food and music from all parts of the world.
Arsenal FC is his favorite team.

Comments and Discussions

 
QuestionDid you realize... Pin
Nelek22-Nov-16 9:53
protectorNelek22-Nov-16 9:53 
AnswerRe: Did you realize... Pin
Shivi Gupta Lucknow20-Dec-16 19:30
professionalShivi Gupta Lucknow20-Dec-16 19:30 
GeneralRe: Did you realize... Pin
Nelek21-Dec-16 1:21
protectorNelek21-Dec-16 1:21 
GeneralRe: Did you realize... Pin
Shivi Gupta Lucknow22-Dec-16 17:48
professionalShivi Gupta Lucknow22-Dec-16 17:48 
GeneralRe: Did you realize... Pin
Nelek24-Dec-16 12:50
protectorNelek24-Dec-16 12:50 
SuggestionGive Some more Details Pin
aarif moh shaikh3-Oct-14 23:55
professionalaarif moh shaikh3-Oct-14 23:55 
GeneralRe: Give Some more Details Pin
Shivi Gupta Lucknow5-Oct-14 22:21
professionalShivi Gupta Lucknow5-Oct-14 22:21 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.