简体   繁体   中英

RegisterStartupScript no longer working in asp.net

Mostly my website is working with ajax, but if I need to send a message on page load I want it to be in the same style as everywhere else, so I am using the following method on my master page:

public void showWarning(String message)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(),"svrShowWarning","showWarning('" + message + "');",true);
}

This was working fine, but recently it has stopped working (I don't know when, exactly.)

The server simply fails to put the script on the page at all - looking at the page source in my web browser, I can see that the script is not present.

Before, I had a form with a runat=server tag enveloping all the content on my master page, but I took this out. I wondered if this may be the cause?

What is a good way to get some simple javascript like this to fire on my page, after everything has loaded?

As ASP.NET Webforms needs a form with a runat=server attribute in order to work correctly, this could be the cause.

Having a look at the documentation , it says that the script is added just before the element

so you probably need that form.

Regarding running the script when everything has been loaded, you could fire it in the onload event of the window object:

public void showWarning(String message)
{
    string script = "window.onLoad(function(){showWarning('" + message + "');});";
    Page.ClientScript.RegisterStartupScript(this.GetType(),"svrShowWarning",script",true);
}

if you are using jQuery on your page, you could use

string script = "$(document).ready(function(){showWarning('" + message + "');});";

instead

With Ajax, using ScriptManager to register scripts is reccomended:

ScriptManager.RegisterStartupScript(Page, GetType(),
       "svrShowWarning","showWarning('" + message + "');",true);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM