[英]ASP.NET: Update ListView from CodeBehind
因此,我的ASP.NET頁上有一個ListView元素,我需要能夠從后面的代碼中進行更新。 據我了解,Microsoft為此恰好准備了UpdatePanels和DataBindung,使我可以將ListView的內容“綁定”到后面代碼中的屬性成員上,並承諾在屬性更改時會自動更新瀏覽器的視圖(?)。 。 但是,只有通過GetStuff()
進行的項目初始加載有效; 我在調試控制台中看到我的計時器一直在向列表添加新元素,但是這些元素永遠不會到達瀏覽器的視圖中。 我想念什么?
在Default.aspx中:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="myLittleProject.Default" %>
<%@ Register Src="~/StuffListItemControl.ascx" TagPrefix="stf" TagName="StuffListItem" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<!-- some irrelevant stuff -->
</head>
<bod>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"></asp:ScriptManager>
<!-- some irrelevant stuff -->
<asp:UpdatePanel runat="server" ID="StuffUpdatePanel" UpdateMode="Always">
<ContentTemplate>
<ul>
<asp:ListView ID="StuffBoundContent" runat="server">
<ItemTemplate>
<stf:StuffListItem runat="server" ID="StuffListItemControl" />
</ItemTemplate>
</asp:ListView>
</ul>
</ContentTemplate>
</asp:UpdatePanel>
<!-- some more irrelevant stuff -->
</form>
</body>
</html>
在Default.aspx.cs中:
using System.Collections.Generic;
namespace myLittleProject
{
public partial class Default : System.Web.UI.Page
{
public static List<Stuff> StuffContent;
protected void Page_Load(object sender, EventArgs e)
{
StuffContent = Stuff.GetStuff(); // returns a list of three elements from the database
System.Timers.Timer t = new System.Timers.Timer();
t.Interval = 3000;
t.Elapsed += T_Tick;
t.Enabled = true;
}
protected void Page_PreRender(object sender, EventArgs e)
{
StuffBoundContent.DataSource = StuffContent;
StuffBoundContent.DataBind();
}
private void T_Tick(object sender, EventArgs e)
{
StuffContent.Add(new Stuff(StuffContent.Count + 1, DateTime.Now.ToShortDateString(), new string[] { "what", "ever" }));
System.Diagnostics.Debug.WriteLine("[TIMER EVENT] StuffContent.Count = " + StuffContent.Count.ToString());
}
}
}
System.Timers.Timer
不適用於網頁。 在將頁面發送給客戶端之后處理t
的原因。 如果您真的想使用一個計時器控件。
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick"></asp:Timer>
然后可以在Timer1_Tick
更新ListView。
protected void Timer1_Tick(object sender, EventArgs e)
{
//update the ListView
}
如果您不希望在觸發計時器時進行完整的回發,請將計時器控件放在UPdatePanel中。
要記住的另一件事是,盡管您使用UpdatePanel,但是會觸發完整的頁面生命周期。 因此,即使在用戶僅可見ListView更新的情況下,也會執行在頁面加載(和PrerRender)中使用的所有其他代碼。 每隔幾秒鍾觸發一次更新面板時,這可能會對服務器造成巨大的負擔。 也許更好地使用Ajax。
PS,您不需要使用Page_PreRender
來綁定數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.