I have a global function that returns some string. I need to access to that function from JavaScript in one of the pages and set returned value to JavaScript variable.
Example:-
var jsvariable = <%GlobalClass.MethodReturningString();%>;
How to do that?
You cannot call C# function like this. you need to create a web service or webmethod in order to call this function. Please see this link it will help you. http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx
Perform the following steps :
context.Response.Headers.Clear(); context.Response.Write(GlobalClass.MethodReturningString();); context.Response.Flush();
context.Response.Headers.Clear(); context.Response.Write(GlobalClass.MethodReturningString();); context.Response.Flush();
In your javascript, perform an ajax call using jQuery :
$.ajax({ url:'someUrl/Handler.ashx', type:'GET', success : function(data){ var someJavascriptVariable = data; } });
NOTE: This is a quick and dirty write so I'm not guaranteeing that the code will surely work, but it's a point for you to start with.
May i thick You cannot do this but u can access ur c# function using ajax
For Example
$.post('url', {parameter : parameter }, function (result) {
// here the result is your function return value or output
},"json");
URL FORMAT : '/pageurl/methodname'
First of all, as a clarification, it seems that you're not trying to actually call a C# method from Javascript, but rather render the return from a C# method inside the page so that it can be used as a Javascript variable value on the client side.
In order to do that you need to update you syntax like:
var jsvariable = '<%= GlobalClass.MethodReturningString() %>';
Please note that if your class is not in the same namespace as the inherited page from the code behind file, then you need to import its namespace like below:
<%@ Import Namespace="GlobalClassNamaspace" %>
The namespace import can also be done globally (and it will be automatically available in all of the site's pages), using the web.config file as described here .
If you were to actually need to call a C# method from Javascript, which would have been needed if you wanted to dynamically use its results from client side code, then that could be accomplished through Ajax .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.