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...)
Related
When using WebView2 it's possible to call C# methods from JavaScript on the web page by exposing a C# class in WebView2 under window.chrome.webview.hostObjects.sync.NameOfMyApiInterface.
Where you can name the NameOfMyApiInterface what ever you like using:
this.MyWebView2Control.CoreWebView2.AddHostObjectToScript("NameOfMyApiInterface", this);
But I've seen those using other 3rd party Chromium browser plugins putting their API directly under window, like window.NameOfMyApiInterface.
Is this possible using WebView2?
Yes. Although calls to CoreWebView2.AddHostObjectToScript will create proxy objects in script on chrome.webview.hostObjects, you can copy those objects wherever you like. You can make a property on window and have it point to the same proxy object.
For example, if you have an object NameOfMyApiInterface that has a property named Property with value "Example":
console.log(chrome.webview.hostObjects.sync.NameOfMyApiInterface.Property); // 'Example'
window.NameOfMyApiInterface = chrome.webview.hostObjects.sync.NameOfMyApiInterface;
console.log(window.NameOfMyApiInterface.Property); // 'Example'
If you call CoreWebView2.AddHostObjectToScript before navigating to the page that will use NameOfMyApiInterface, you can update that page to do the assignment at the top before other script runs. Or if you don't own or can't update the page, you can use CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync to add the line of script that does the assignment to run before any other script in that page.
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
In my asp.net websites I regular uses the following methods before actually adding either custom pieces of script or registering a js file:
IsClientScriptBlockRegistered(Type, String)
IsClientScriptIncludeRegistered(Type, String)
When a page requires a custom piece of script, somewhere during PageLoad I call IsClientScriptBlockRegisterd() followed by RegisterClientScriptBlock().
if (!Page.ClientScript.IsClientScriptBlockRegistered(typeof(Page), "myKey"))
{
// Start creating ScriptBlock //
// .. //
// Actually Register the script //
ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(Page), "myKey",
sbScript.ToString(), false);
}
The above code is always called once during a postback.
When a user is on the related page, while staying on that page he can cause multiple postbacks (actual postbacks, not callbacks).
During a postback the GetRegisteredClientScriptBlocks method always returns an empty collection. So IsClientScriptBlockRegistered always returns false. Therefore, for each postback I have to recreate the custom scriptblock and re-register it with the page, and re-send it to the client.
Is there a way to register a custom scriptblock and let it exist at the client for as long as the user stays on the related page, or for as long as the users sessions is active?
Thanks in advance.
Assuming you are using ASP.Net WebForms, you may use the following property to ensure whether it is postback or not:
Page.IsPostback()
Alternatively, you may pass some sort of flag/cookie/hidden variable indicating that this particular page does not need any client scripts to be registered.
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.
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.