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 :
Right click on your website or web application and add a WebHandler. The extension for the webhandler is '.ashx'. Let's say you name your handler as 'Handler.ashx'
Open the Handler.ashx file and within the ProcessRequest method write the following :
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.
Related
I'm in the code behind of a generic http handler (.ashx) and I'd like to get a reference to the instance of the calling .aspx page, so I can call some methods/get some properties of it. I can easily call static methods of the page, but I'm not able to get the actual object instance.
Is there a way, without resorting to services/webmethods/whatnot? Thanks!
EDIT:
I call the ashx from the JS inside the aspx page
$.ajax({
url: "handler.ashx",
context: "my content"
}).done(function() {
alert("Done");
});
Then I update an asp:Label with the result of it.
I've found a way to do it anyway (you can do it via JQuery from JS for instance), but now I'm curious if you can do it from the code behind simply calling some pageInstance.setMyLabel(ashxResult) or something like this.
There is no direct way to modify the contents of your calling .aspx-page via server-side code.
You should (like you mention yourself) process the results of the call to your .ashx-handler with javascript.
If you would like to use some results 'serverside' I think the only option is that you write some data to the session-object during the processing of the .ashx-handler.
On the next postback of the .aspx-page you could use that data to accomplish some change. If you would like to do that, please refer to this question also:
How to access Session in .ashx file?
The instance of the page class only exists for as long as it takes to process the request and send the response back to the client. By the time the Javascript code executes and makes a request to the ashx file, the page instance has been destroyed.
ASP.NET Page Life Cycle Overview | Microsoft Docs
I want to pass some javascript parameters at runtime (webplayer) to unity and using them in my network.cs script.
<html>
<script type="text/JavaScript">
//<![CDATA[
PlayerName = "Adam";
playerID = "56";
//]]>
</script>
</html>
Just consider I am using the above parameters to log in users.
You need to send the data from the webpage to the Unity3d container. You can do something like this:
u.getUnity().SendMessage(GameObjectName,MethodName,stringParam);
where:
u is the Unity3d container object created by unity if you use their template.
GameObjectName is the name of a game object that you placed somewhere on the stage
MethodName is the name of a method that's available for that GameObject, that means that it will be a method defined in one of the components (MonoBehaviour) that you attached the the GameObject
stringParam si the parameter that you pass to MethodName, the method can only accept one string param, so you need to serialize your data, you can use JSON.parse( {"playerName":PlayerName,"playerId":playerID} )
On the C#/Unity side you need to implement a MonoBheviour that has a
void MethodName(string param);
defined that reads the string and with a JSON parser gets the data out.
You would need to post that data back to your server. Using AJAX is probably want you want if you don't want your whole page to reload.
A commonly used framework, facilitating ajax is jQuery.
You would need an endpoint, writting in your c# (guessing from your fileending on network.cs) to read what your clientside javascript is posting. I don't know what version of .net you are on, but look into WebAPI - it is very easy to implement.
TL;DR
Use javascript/jquery to post your data from the client to the server.
Read the posted data on your serverside, though either WebAPI or just a normal .aspx page reading querystring/form values
If you just want to send data from the client, and not worry about any response, you can use
$.ajax({
type: "POST",
url: url,
data: {PlayerName: PlayerName, PlayerId: playerID},
});
You can change POST to GET if you want the make a get request instead. The data will be readable through Request.Form or Request.QueryString if you use a normal .aspx page for url. If you use WebAPI, it will be injected into your methods parameters.
I am using prototype, and i have a function as follows:
MyJSClass.prototype.AddLetters = function()
{
}
I would like to call this from c# based on some conditions i need to evaluate on pre-render.
Hello you can try with this code
ClientScriptManager cs = Page.ClientScript;
String yourScript= "function();";
cs.RegisterStartupScript(this.GetType(), "key script", yourScript, true);
Since you can't directly call JavaScript code from C# - especially before the page is rendered, you need a way of:
communicating the requirement/condition to the JavaScript code
picking up and appropriately dealing with the requirement/condition at the right time.
For 1. I recommend using the ClientScriptManager to insert/modify a variable, although there are other options below.
For 2. you should probably add some javascript which will pick up the communication.
Options for 1.:
Add a field into the page
Add a script into the page (e.g. using the Client ScriptManager) which will set a variable
Inject the script into the page directly at the relevant point for it to run
set a flag in the C# which you then check when you receive an AJAX call (which you might use if it will change according to server-side rules while the page is open...)
I have a tricky problem. I am in a situation where I need to use a method defined in a .cs file from a javascript function. The problem is we are using .NET 1.1 and AJAX cannot be used for the application.
Also, I will need to pass a string from the javascript to the server side method. The page where I am implementing the javascript is a .as Any ideas?
I have tried doing a post back and creating a RaisePostBack event handler method (both in the .aspx page and the .ascx user control) but no luck.
It will be greatly appreciated if someone could help me out with the problem.
To be more precise. I have a class Attachment.cs which has a method Delete().
The javascript is called from a span's onclick event. The javascript function's input parameter would be a string which I will need to use to instantiate an Attachment.
I created a method which instantiates an Attachment using a string and calls the corresponding Delete() method for the Attachment object.
Now, I will need to pass the string from javascript function to the method I have created. I cannot use PageMethods.
The Javascript function is like:
// File ID is a string
function DeleteAtt(fileID)
{
//I tried PageMethods here, tried posting the page and getting the value through
// a RaisePostBack event etc. No luck.
}
The cs method I created is like:
public void DeleteAttachment(string ID)
{
Attachment obj = new Attachment(ID);
obj.Delete();
}
Do you mean that Microsoft's "ASP AJAX" is not an option, or do you mean that any jquery/any other library, or your own hand written javascript ajax won't work? ASP AJAX may not be supported by you version of .net, but surely simple javascript will still work, as you want to access the page from javascript.
If this is the case, something as simple as this, using jquery, would work:
function submit() {
$.post(
"pagename.aspx?string=" + variable,
function (data) {
alert("Response: " + data);
});
}
How about adding a callback-url as a query string to the url that you need to submit data to? Example:
Initial Page:(javascript)
function send(){
window.location = "submiturl.aspx?str=var&
callbackurl=http://www.myurl.com/page.aspx";
}
submiturl.aspx then catches both query strings [str] and [callbackurl], performs the action/function and then sends a response back to the [callbackurl]
response.redirect(callbackurl + "?response=" + data);
Initial Page now uses response.querystring to determine if it was succesful/whatever else you want and continues its business.
This definitely does not use ajax, and would be, by no means, asynchronous, but is based on a pretty lengthy history of API/callback & response design.
You can inject an invisible Iframe into the page and the SRC of the iframe can be used to pass data back to the server.
This is a very old technique back before jQuery and Prototype were invented.
See: http://www.ashleyit.com/rs/ for other alternatives.
For an Umbraco project, I am trying to make a simple Ajax call.. I can't use PageMethods because I need to make the call from inside a UserControl..
I tried to do it via web service call like this:
Web service method:
[System.Web.Script.Services.ScriptService]
public class MapService : System.Web.Services.WebService
{
[WebMethod]
public static string GetCities(string ProvinceCode)
{
return "foo";
}
}
JS part in my ASCX file:
<script language="javascript" type="text/javascript">
function callServer(src) {
MapService.GetCities(src, displayMessageCallback);
}
function displayMessageCallback(result) {
fillDDL(result);
}
</script>
The problem is, "MapService.GetCities" method doesn't get invoked..
What might be the problem here?
Alternatively, what is there any better way to make these kind of Ajax calls in a User Control?
I've been usign the Umbraco base REST Extensions for this kind of thing. I think it's a lot simpler to implement and if you use a JSON Serialiser on the server you even have proper JSON objects on the client.
Use REST method for doing this. we have implemented this for our projects. For this you have to edit the restExtensions.config and add your entry.
I think the problem might be that the javascript inside the usercontrol does not communicate with the scriptmanager in the page.
I can see two ways of dealing with this.
1. Use jQuery to call the webmethod instead of asp.net ajax.
2. through the control javascript call a method in the page javascript which will call the webmethod, i.e. use the page as a proxy. This has the added advantage of enabling you to use a page method instead of a web service.