I'm having some issues accessing a static variable in a class when getting it from a code behind function called from javascript.
My aspx page:
<script type="text/javascript">
function AlertMsg(msg) {
var msg213 = "<%= GetValue(" msg ") %>";
alert(msg + '::' + msg213);
}
</script>
Code behind:
public string GetValue(string sString)
{
return MyNamespace.MyClass.MyStaticVariable;
}
I set this variable in a page_load in another page. I'm accessing the javascript function by invoking it from a C# WebBrowser application. It's always empty.
Any ideas?
I think you just need to add '+' around your reference to 'msg'
var msg213 = "<%= GetValue(" + msg + ") %>";
ASP.NET isn't like a desktop application, any variables written on another page will be lost when moving to another page. You need to save the value to somewhere persistent.
Session
Cache
Database
App or Web Config files.
Variable needs to be a const or static
Try this
'<%= GetValue("Some Value") %>';
This means when page rendering, GetValue method calls and return string will be write in the document body, like Respose.Write
This will only happend when when page rendering and no further call will happend.
I think part of the confusion is coming from the formatting in the code. If you look at just the server tag: <%= GetValue(" msg ") %>, you will see that the GetValue method is being invoked, and the literal string msg is being passed in. There are quotes around the server tag itself, but those do not affect what is inside the server tag. You are not passing in the value of the msg parameter of the JavaScript function.
Server methods cannot be invoked from JavaScript in such a simple manner, it requires using something like AJAX to accomplish.
Related
I want to assign viewbag to my javascript variable to compare some value from model
<script>
var uid = "..."; // this retrieves some variable from external server
#ViewBag.someId = uid;
</script>
...
#If(Model.AppDataFbId == ViewBag.someId){ ... }
But this throws an exception:
Uncaught SyntaxError: Unexpected token =
What can I do?
As the comment said , ViewBag is server side code, you can't set ViewBag with js variables in C# code block but you can set js variables with ViewBag value. Like:
<script>
var uid ='#ViewBag.someId';
</script>
If you just want compare Model.AppDataFbId with js variable(uid), add the logic in js code.
<script>
function compare(){
if('#Model.AppDataFbId'==uid){
//other code
}
}
</script>
The variable #ViewBag.someId is used by the server to generate the static HTML page it sends to the browser. It doesn't make sense for the browser to be able to directly change that variable on the server after it receives the HTML.
It looks like you want the value of uid to decide the page contents. If you want these changes to be made server-side (i.e. before the page is sent to browser) then you will have to get your MVC controller to grab this value from the external server before it returns its view. A more conventional way to solve the same problem is to transform the page in the browser with Javascript.
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 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.
How can I call a javascript function, that is in the aspx page, from the Page_Load method, in the code-behind?
The simple answer is, you can't. The code in the Page_Load method executes on the server, javascript executes on the client.
If what you want to do is add a call to a javascript method, in the Page_Load so that once the page is loaded by the browser, the javascript executes, then you can use the ScriptManager:
if (myConditionForAddingCallToJavascriptIsMet)
{
Page.ClientScript.RegisterClientScriptBlock(typeof(ScriptManager), "CallMyMethod", "myMethod();");
}
else
{
// Do something else, add a different block of javascript, or do nothing!
}
To use this, you'll need to have an <asp:ScriptManager> element in your markup for it to use (if memory serves, an exception will be thrown if you don't have one). The text "CallMyMethod" is used by the ScriptManager to uniquely identify the script that it injects for you, and the text "myMethod();" is embedded, so you'll end up with an additional script element in your page similar to this:
<script language="javascript" type="text/javascript">
myMethod();
</script>
The easiest way is to use the page's ClientScript property. You can register some code to run when the page loads using something like
ClientScript.RegisterStartupScript(GetType(), "hiya", "alert('hi!')", true);
See http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx for more info.
This should be available from a child control by tacking "Page." onto the beginning of the code above.
Why would you want to do this?
What's the purpose?
Anyway you can do the following, but I DON'T recommend it!!! :
protected void Page_Load(object sender, EventArgs e)
{
string pagename = "Test.aspx";
String scriptString = "<script language=JavaScript> function DoClick() {";
scriptString += " window.showModalDialog('" + pagename + "' )}";
scriptString += "</script>";
if(!this.IsStartupScriptRegistered("Startup")) //This is **not** a good practice
this.RegisterStartupScript("Startup", scriptString);
}
Can you supply with more information of what you want to achieve to get better answer..
Shide's solution works. The problem is if you want to run your piece of code only on postback, for example. The solution I found was to use a "cookie": I verify if cookie x exists, if it doesn't I run the javascript code and set the cookie. When you hit refresh, the cookie will be found so the piece of code won't run.
function pageLoad() {
if(localStorage.getItem("cookie") === null) {
localStorage.setItem("cookie", true);
//run code
}
}
Any code you need to run every single time just leave it out of the if statement.
You need to use Register client Script:
MSDN
CodeProject
I do it in a Page Load method:
if (!this.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "HelpScript"))
{
var scriptSource = "function ShowHelp() { alert(""); };\n";
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "HelpScript", scriptSource, true);
}
but I don't think it's recommended
I mean... you can do this, and it'll work. But for me the only good reason of inserting a script from asp.net page is to get some client side features of server controls.
So for example to get an instance of control:
var myControlId = this.control.ClientID;
But writing entire javascript functions and logic on the server side is not comfortable when you need to change it or debug it (for me it's hardcoded string).
If you just want to call a JavaScript function ( and do not need to pass something from code-behind, then use this...)
document.onload = function () { your-function(); };
window.onload = function () { your-function(); };
document.readyState = function () { your-function(); }
... depending on your specific requirements.
Hope this makes sense to you & answers your question.
this is a little trick i found myself without having server side code .
that function will be called when the page loads (can be used with an update panel) :
<script>
function pageLoad() {
//Do your stuff
}
</script>
it is unknown and yet works like a charm
Please try this code:
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "test();", true);