albvar
albvar

Reputation: 76

ASP.NET and C# retain dynamically added <li> content on post back

Issue Definition

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. I am dynamically adding <li> tags in the C# code behind page see example provided. I am trying to retain this information across post backs. Any help is greatly appreciated.

ASP.NET Code

<%@ 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>

C# Code

    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);
    }

Upvotes: 0

Views: 850

Answers (1)

Silvos
Silvos

Reputation: 175

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

<%@ 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

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.

Upvotes: 1

Related Questions