以编程方式在UpdatePanel中添加用户控件

我在使用部分回发在更新面板中动态添加控件时遇到问题。 我已经阅读了许多关于动态控件的文章,我了解如何使用回发添加和维护它们,但大多数信息不适用,并且不适用于部分回发。 我找不到有关使用UpdatePanel添加和维护它们的任何有用信息。 如果可能的话,我想在没有创建Web服务的情况下这样做。 有没有人对某些有用的信息有任何想法或参考?

我认为,这是asp.net程序员常见的陷阱之一,但实际上并不是很难在你知道发生了什么事情时做到这一点(永远记住你的观点!)。

以下代码解释了如何完成任务。 这是一个简单的页面,用户可以单击菜单,该菜单将触发一个操作,该操作将向updatepanel内的页面添加用户控件。
(此代码是从这里借来的,并且有关于此主题的更多信息)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu1.aspx.cs" Inherits="SampleMenuPage1" %>    Sample Menu   


 using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class PlainSampleMenuPage : System.Web.UI.Page { private const string BASE_PATH = "~/DynamicControlLoading/"; private string LastLoadedControl { get { return ViewState["LastLoaded"] as string; } set { ViewState["LastLoaded"] = value; } } private void LoadUserControl() { string controlPath = LastLoadedControl; if (!string.IsNullOrEmpty(controlPath)) { PlaceHolder1.Controls.Clear(); UserControl uc = (UserControl)LoadControl(controlPath); PlaceHolder1.Controls.Add(uc); } } protected void Page_Load(object sender, EventArgs e) { LoadUserControl(); } protected void Menu1_MenuItemClick(object sender, MenuEventArgs e) { MenuItem menu = e.Item; string controlPath = string.Empty; switch (menu.Text) { case "Load Control2": controlPath = BASE_PATH + "SampleControl2.ascx"; break; case "Load Control3": controlPath = BASE_PATH + "SampleControl3.ascx"; break; default: controlPath = BASE_PATH + "SampleControl1.ascx"; break; } LastLoadedControl = controlPath; LoadUserControl(); } } 

对于背后的代码。

基本上就是这样。 您可以清楚地看到,当控件本身被动态添加到页面时(在updatePanel内部(实际位于updatePanel内的placeHolder内),当用户单击菜单项时,将使用LastLoadedControl保持视图状态,这将发送异步回发到服务器。

更多信息也可以在这里找到:

当然还有保存我在这里使用的示例代码的网站 。

我遇到了使用上述方法的问题,在处理事件时调用了两次LoadUserControl()。 我已经阅读了其他一些文章,并希望向您展示我的修改:

1)使用LoadViewstate而不是Page_Load加载用户控件:

 protected override void LoadViewState(object savedState) { base.LoadViewState(savedState); if (!string.IsNullOrEmpty(CurrentUserControl)) LoadDataTypeEditorControl(CurrentUserControl, panelFVE); } 

2)加载usercontrol时不要忘记设置控件ID:

 private void LoadDataTypeEditorControl(string userControlName, Control containerControl) { using (UserControl myControl = (UserControl) LoadControl(userControlName)) { containerControl.Controls.Clear(); string userControlID = userControlName.Split('.')[0]; myControl.ID = userControlID.Replace("/", "").Replace("~", ""); containerControl.Controls.Add(myControl); } this.CurrentUserControl = userControlName; } 

试试这个:

 Literal literal = new Literal(); literal.Text = " 

您可以将文字内容替换为您想要的任何HTML内容...