How can i call a javascript function in the page_load event of a asp.net c# web application
I also want to pass a variable to that javascript function.
JavaScript is client-side code.
Page_Load is server-side code.
You can't call one directly from the other. The next best thing is to arrange for your client-side code to be called when the page loads in the browser. You can do that by dynamically generating your script in-line with the rest of your markup.
You can use Page.RegisterStartUpScript
public void Page_Load(Object sender, EventArgs e)
{
if (!this.IsStartupScriptRegistered("Startup"))
{
// Form the script to be registered at client side.
String scriptString = "<script language=\"JavaScript\"> function DoClick() {";
scriptString += "showMessage2.innerHTML='<h4>Welcome to Microsoft .NET!</h4>'}";
scriptString += "function Page_Load(){ showMessage1.innerHTML=";
scriptString += "'<h4>RegisterStartupScript Example</h4>'}<";
scriptString += "/";
scriptString += "script>";
this.RegisterStartupScript("Startup", scriptString);
}
Depending on your version of .NET you should use
ScriptManager.RegisterStartupScript
the Page level method is deprecated.
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.