Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Call Code Behind Method from Client Side

0.00/5 (No votes)
20 Dec 2016 2  
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

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:ScriptManager ID="ScriptManager1" runat="server" 
EnablePageMethods="true"></asp:ScriptManager>

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

[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:

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

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:

</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:

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:

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.

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:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here