ASP.NET inject javascript in user control nested in update panel

无人久伴 提交于 2020-01-12 03:58:10

问题


I'm trying to load javascript code with a user web control into a page via a the Page.LoadControl method during an asyncron post back of an update panel.

I've tried the specially for that scenario designed methods of the scriptmanager, but the javascript just doens't get returned to the user.

To explain my scenario a bit better:

Master Page has the script manager and one page loads the user control via Page.LoadControl-method during an async post back. The custom control injects in the pre-render event handler the javascript. Is that a matter of timing to inject the js or is it just not possible to do so?


回答1:


For that you can do

string scr;
scr = "<script src='/scripts/myscript.js'></script>"
Page.ClientScript.RegisterStartupScript(GetType(Page), "key", scr, false)

HTH




回答2:


If you don't want to hard-code your JavaScript, but instead include it from a file, call ScriptManager.RegisterClientScriptInclude and then call your initialization function in ScriptManager.RegisterStartupScript.

protected void Page_Load(object sender, EventArgs e)
{
   ScriptManager.RegisterClientScriptInclude(
      this, GetType(), "formatterScript", ResolveUrl("~/js/formatter.js"));
   ScriptManager.RegisterStartupScript(
      this, GetType(), "formatTableFunction", "formatTable()", true);
}



回答3:


Have your tried

Page.ClientScript.RegisterStartUpScript(GetType(Page), "key", <your script here>, addSctiptTags:=true)

We do this in our User Controls and it works for us

HTH




回答4:


You can use the RegisterStartupScript method of the ScriptManager class to inject executable script:

public partial class WebUserControl : System.Web.UI.UserControl
{          
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(this, GetType(), ClientID, "alert(1)", true);
    }
}



回答5:


Putting the RegisterStartupScript in the Page_PreRender event may not work if your control is nested in an asp.net modal popup. Instead, put it in the Page_Load when IsPostBack = False.



来源:https://stackoverflow.com/questions/301471/asp-net-inject-javascript-in-user-control-nested-in-update-panel

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