Jwalin Khatri

Call Server side code from Client side script

Posted by: jwalin on: April 25, 2008

You can call the server side code from client side javascript. Yes, I know you can create web service(.asmx) file and call web service from Javascript but some site for little thing you have to create web service.

Instead of that you create one static method and declare as [System.Web.Services.WebMethod] then on page put the

<asp:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePageMethods=”true”/>

Write script.js file as following
function CallMe(src,dest)
{
var ctrl = document.getElementById(src);
// call server side method
PageMethods.<YOUR SERVER SIDE METHOD>(ctrl.value, CallSuccess, CallFailed, dest);
}

// set the destination textbox value with the ContactName
function CallSuccess(res, destCtrl)
{
var dest = document.getElementById(destCtrl);
dest.value = res;
}

// alert message on some failure
function CallFailed(res, destCtrl)
{
alert(res.get_message());
}
and on Page Load Event

if (!Page.IsPostBack)
{
txtId1.Attributes.Add(“onblur”, “javascript:CallMe(‘” + txtId1.ClientID + “‘, ‘” + txtItem1.ClientID + “‘)”);
txtId2.Attributes.Add(“onblur”, “javascript:CallMe(‘” + txtId2.ClientID + “‘, ‘” + txtItem2.ClientID + “‘)”);
}

That’s it.

Leave a Reply

Blog Stats

  • 16,524 hits

  • Kingsley Tagbo: Thanks for reading and sharing my article. Have a great like ... Kingsley
  • Bob: Doesn't work with IIS7 (default config on Windows 7 and 2008) because no ADSI anymore.
  • jwalin: Follow the following steps 1]. open you Page in NOTEPAD. 2]. find the tag 3]. Replace the "body" like body oncontextmenu=”return false;" 4]. Sav