How can I call a javascript function, that is in the aspx page, from the Page_Load method, in the code-behind?
-
1@scatman - if you have another question, albeit similar, ask a new question rather than muddying the waters munging multiple questions together =) For what it's worth, there's probably enough information in this questions answers for you to work it out yourself after a bit of trial-and-error ;)Rob– Rob2010-04-20 09:16:39 +00:00Commented Apr 20, 2010 at 9:16
8 Answers
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>
Comments
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.
Comments
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..
1 Comment
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.
Comments
You need to use Register client Script:
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).
Comments
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.