[英]ASP.NET and C# retain dynamically added <li> content on post back
Using this basic example to reproduce the issue. 使用此基本示例重现该问题。 When pressing button (causes post back) my <li>
disappears and leaves behind an empty <ol>
tag as expected. 当按下按钮(导致回发)时,我的<li>
消失了,并留了一个空的<ol>
标记。 I am dynamically adding <li>
tags in the C# code behind page see example provided. 我正在页面后面的C#代码中动态添加<li>
标记,请参见提供的示例。 I am trying to retain this information across post backs. 我试图在回发中保留此信息。 Any help is greatly appreciated. 任何帮助是极大的赞赏。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="State.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ol id="myOl" runat="server">
</ol>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:TextBox ID="TextBox1" runat="server" Text=""></asp:TextBox>
</div>
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
EnableViewState = false;
if (TextBox1.Text == string.Empty)
PopulateTextBoxes(TextBox1, myOl);
}
private static void PopulateTextBoxes(ITextControl textBox1, Control bulletedList)
{
textBox1.Text = "TextBox1";
var li = new ListItem`enter code here`
{
Text = "Item1"
};
var bl = new BulletedList();
bl.Items.Add(li);
bl.DataBind();
bulletedList.Controls.Add(bl);
}
Actually I'm not sure what you are trying, but when you want a bullet list, that adds items on each button click try this one: 实际上,我不确定您要尝试什么,但是当您想要一个项目符号列表时,该列表在每个按钮上添加了项目,请单击以下按钮:
ASPX ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:BulletedList runat="server" ID="bulletList"/>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:TextBox ID="TextBox1" runat="server" Text=""></asp:TextBox>
</div>
</form>
</body>
</html>
Codebehind 代码隐藏
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (TextBox1.Text == string.Empty)
{
PopulateTextBoxes();
}
}
private void PopulateTextBoxes()
{
var li = new ListItem()
{
Text = "Item1"
};
bulletList.Items.Add(li);
}
}
Here's some more info about the BulletedList control: MSDN 这是有关BulletedList控件的更多信息: MSDN
When you disable ViewState, the page cannot maintain its state between postbacks, so you should disable it only, when you need to reduce network traffic. 禁用ViewState时,页面无法在回发之间保持其状态,因此仅在需要减少网络流量时才应禁用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.