Call JavaScript function from ASP.net code behind

依然范特西╮ 提交于 2019-12-24 01:40:50

问题


I’m trying to call a JavaScript function from Code behind but no luck so far. I tried to add the following snippets inside Page_Load method.

I’ve tried as below

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "foo", "alert('test22222')", true);

Also as below

Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScript", "alert('test22222');", true);

None worked for me. Is there anything I’m missing here? I would like to show the alert message before loading the page.

Any help appreciated. Thanks.


回答1:


you can implement it in page_prerender event

    protected void page_prerender( object sender, EventArgs e )
{
         your code here;
}



回答2:


You are missing a ; in you code. Try this it worked for me.

But i would suggest the ScriptManager.RegisterStartupScript over the Page.ClientScript.RegisterStartupScript as the first one is designed for AJAX calls. Which will work for even partial page post backs.

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "foo", "alert('test22222');", true);



回答3:


This will work. You forgot semicolon at end of your alert:

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "foo", "alert('test22222');", true);


来源:https://stackoverflow.com/questions/16056777/call-javascript-function-from-asp-net-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!