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.