ang*_*elo 13 c# asp.net asp.net-ajax
我在使用部分回发在更新面板中动态添加控件时遇到问题.我已经阅读了很多关于动态控件的文章,我理解如何使用回发添加和维护它们,但大多数信息不适用,不适用于部分回发.我找不到有关使用UpdatePanel添加和维护它们的任何有用信息.如果可能的话,我想在不创建Web服务的情况下这样做.有没有人对某些有用的信息有任何想法或参考?
sve*_*ven 10
这是,我认为,对于asp.net程序员的常见问题之一,但实际上并没有那么很难得到它的权利,当你知道是怎么回事(永远记住你的浏览状态!).
以下代码解释了如何完成任务.这是一个简单的页面,用户可以单击一个菜单,该菜单将触发一个操作,该操作将向updatepanel内的页面添加用户控件.
(此代码是从这里借来的,并且有更多关于此主题的信息)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SampleMenu1.aspx.cs" Inherits="SampleMenuPage1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Sample Menu</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Menu ID="Menu1" runat="server" OnMenuItemClick="Menu1_MenuItemClick">
<Items>
<asp:MenuItem Text="File">
<asp:MenuItem Text="Load Control1"></asp:MenuItem>
<asp:MenuItem Text="Load Control2"></asp:MenuItem>
<asp:MenuItem Text="Load Control3"></asp:MenuItem>
</asp:MenuItem>
</Items>
</asp:Menu>
<br />
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Menu1" />
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
和
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();
}
}
Run Code Online (Sandbox Code Playgroud)
对于背后的代码.
基本上就是这样.您可以清楚地看到,当控件本身被动态添加到页面时(在updatePanel内部(实际位于updatePanel内的placeHolder内),当用户单击菜单项时,将使用LastLoadedControl保持视图状态,这将发送异步回发到服务器.
更多信息也可以在这里找到:
归档时间: |
|
查看次数: |
22899 次 |
最近记录: |