Sys.Application.add_init Not Invoked on UpdatePanel Update
I have a custom UI control which has a JavaScript class written around the AJAX.NET framework. It inherits from the Sys.UI.Control. The control itself is a UserControl. In the render method I wrap the control in a span and give the span's id the ClientID of the user control. This way I can do this later on:
var control = $find('<%= ServerControlID.ClientID %>');
This allows me to get the client object that represents the UI control.
I create the control in Javascript by doing this (also in the render method)
writer.Write(@"<script type='text/javascript'>
Sys.Application.add_init(function() {
debugger;
$create(General.Filters.AccountGroupFilter,
" + GetProperties() + @",
null,
null,
$get('" + this.ClientID + @"'));
});
</script>");
This creates the object. It's done inside of the init event of the life cycle.
The problem is that this control is wrapped inside of an UpdatePanel by a consuming page/control. When another control initiates an update all the controls' UIs get redrawn, BUT the init event NEVER FIRES again.
What happens then is when I do this:
var control = $find('<%= ServerControlID.ClientID %>');
if(control != null)
control.doSomething();
Nothing happens because the $find does not find the control after the AJAX call. I know I'm NOT doing this correctly. Where am I going wrong. The MSDN article for this stuff is pointing me in circles!
EDIT: Figured I'd include the Render method that I'm doing in the UserControl.cs portion
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<span id=\"" + this.ClientID + "\" >");
writer.Write(@"<script type='text/javascript'>
Sys.Application.add_init(function() {
$create(TradePMR.OMS.Resources.UserControls.General.Filters.AccountGroupFilter,
" + GetProperties() + @",
null,
null,
$get('" + this.ClientID + @"'));
});
</script>");
base.开发者_运维技巧Render(writer);
writer.WriteEndTag("span");
}
You don't need to write all that Sys.Application.add_init
stuff yourself; implement IScriptControl
as per this MSDN article.
The key is the part about RegisterScriptControl
and RegisterScriptDescriptors
, which registers your control with the ScriptManager
so that an async postback will recreate your client control as necessary.
As a footnote, there is a seperate but similar article here if you are implementing Sys.UI.Behavior
instead.
精彩评论