创建 ASP.NET AJAX 服务器控件。覆盖 RenderContents 方法,我将代码放入如下所示:
protected override void RenderContents(HtmlTextWriter writer)
{
var updatePanel = new UpdatePanel();
updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
updatePanel.ClientIDMode = ClientIDMode.AutoID;
updatePanel.ID = "CaptchaUpdatePanel";
updatePanel.ChildrenAsTriggers = true;
//var placeHolder = new PlaceHolder();
var hiddenField = new HiddenField();
hiddenField.ID = "captchaKey";
updatePanel.ContentTemplateContainer.Controls.Add(hiddenField);
var panel = new Panel();
panel.ID = "Captcha";
var imgButton = new ImageButton();
imgButton.ID = "RefreshCaptcha";
imgButton.TabIndex = 0;
imgButton.AlternateText = "Refresh Captcha Characters";
imgButton.ImageUrl = RefreshButtonPath;
imgButton.Width = 36;
imgButton.Height = 36;
panel.Controls.Add(imgButton);
updatePanel.ContentTemplateContainer.Controls.Add(panel);
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = "CaptchaRefresh";
trigger.EventName = "Click";
updatePanel.Triggers.Add(trigger);
updatePanel.ContentTemplateContainer.RenderControl(writer);
base.RenderContents(writer);
}
编译控件并将其放到 Web 窗体页面上,我发现 UpdatePanel 不起作用。UpdatePanel 中的按钮在单击时会执行完整的回发,而不是异步执行。
没有成功,我一直在网上搜索答案。
我想知道在 AJAX 服务器控件中使用 UpdatePanel 是否是个好主意。我已经使用 UserControl 成功地执行了这个类似的任务。
HTML 脚本如下:
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register Assembly="CaptchaControl" Namespace="CaptchaControlx" TagPrefix="cc1" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
}
</script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<cc1:captcha runat="server" />
</form>
</body>
</html>