问题
When the page initially renders, the initializeControl
function is called and everything works.
When the page performs a full post-back (via a submit button), the initializeControl
function is also called and everything works.
When there is partial post-back of the UpdatePanel
, though, the initializeControl
function is never called and the control stops working.
HTML:
<asp:ScriptManager ID="myScriptManager" runat="server" />
<asp:UpdatePanel ID="myUpdatePanel" runat="server">
<ContentTemplate>
<uc:MyControl ID="myControl" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
User Control:
Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)
Dim initializeScript = String.Format("initializeControl('{0}');", ClientID)
Page.ClientScript.RegisterStartupScript(GetType(Page),
New Guid().ToString(), initializeScript, True)
MyBase.Render(writer)
End Sub
For testing purposes, assume the initializeControl
function is just a debugger;
(the content of the function works fine - it's just not being called when it needs to be).
Please keep in mind that there is no way (that I know of) for the user control to know if it is inside an UpdatePanel
or not, and there is also no way it can access the ScriptManager
element on the parent page in server code.
Thanks in advance.
P.S. I know UpdatePanel
s are awful and should be avoided at all costs, but I am working with hundreds of consuming pages that are already using them and they can not be changed.
回答1:
It's most likely due to the fact that the page update is happening through the update panel. Startup scripts can have issues with not firing in these cases, and need to be wrapped in:
Sys.Application.add_load(function(){ myFunctionCall(); });
It's the Microsoft AJAX library's way of ensuring your startup script happens when it should during MS AJAX roundtrips.
Here's an easy way to ensure all client scripts added to the page work, regardless of whether they are contained in an ajax updatepanel or not. We use this in all of our projects and it works flawlessly:
ASP.Net - Javascript inside AJAX UpdatePanel
来源:https://stackoverflow.com/questions/12917821/injecting-javascript-from-a-user-control-inside-an-updatepanel