Thursday, March 11, 2010

Calling server side code from javascript

Found a good article on how to do this ... Posting some intercepts here
You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.
One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.

The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.

Example
C#
[System.Web.Services.WebMethod]
public static string GetContactName(string custid)
{
}
Javascript function calling server method
function CallMe(src,dest)
{
var ctrl = document.getElementById(src);
// call server side method
PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
}
//

And here's the source http://sappidireddy.wordpress.com/2008/03/31/how-to-call-server-side-function-from-client-side-code-using-pagemethods-in-aspnet-ajax/

Coffee time

Sometimes coffee time talks though very brief have lot of depth.... It generally starts with gossip but the climax rather take way is so wise that the gossip that started it even starts looking worth :D .... Not to miss on today's climax....When you have to choose between being smart or genuine, I would say genuine. Counting on no of people I met were smart, there were many but those who were genuine i could count on fingers... and that's when i occured that the latter is rare....And yea genuinely smart is rarer :) ..
With that note Shubraatri