views:

94

answers:

3

How can i execute a C# method in a java script function? Is it possible?

+2  A: 

What you can do is fire an AJAX call that executes a C# method on the server, and hands back the result to the javascript.

AJAX is best handled with a javascript framework such as jQuery.

David Hedlund
+1  A: 

Yes it is possible to access the server side methods in C# using Javascript For all you need to use write a static function in the server side and call it using PageMethods.

at Client Side

   PageMethods.FunctionName(para1,pageMethodError)
    Here the condition is to pass pagemethoderroe as a parameter to return the function fails
         PageMethods.Get(Id,
                    function(result) {
                          $(.res).html(result);
                           }

                        }
                    }
                    , pageMethodError);

 pageMethodError=function(error){
  //code if failed
 //error will return error message
}

at server side

[System.Web.Services.WebMethod]

        public static object Get(string ID) {
            return "hai";
        }

for more abt the parameters for a Page method plz refer to http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.3

This method is also using Ajax and it will post your request to the server and the server responds in the form of JSON [JavaScript object notation].So there is no problem if your server is located in US and accessing from China

Vishnu K B
+4  A: 

Not really. If you server is located in the USA, and a user visits your site from China, your C# code will execute in the USA, and your JavaScript code will execute several moments later (~ 500ms later probably) in China. When the JavaScript code begins its execution, the C# script that ran on the USA server will be long forgotten and terminated.

Your best bet is probably to communicate back to your server through Ajax, as @David suggested in the other answer.

Daniel Vassallo
@Daniel PageMethods is also working as Ajax.So I hope there will be no problem will come.
Vishnu K B