I figured out how to create headers and append it to my html div, but if I press the button to create and append twice, it overwrites the other one. I want it so if I press the button twice, the new header will appear underneath, and not overwrite.
HTML
<div class="tools">
<asp:Button ID="HeaderOne" class="tool" runat="server" Text="Header 1" Height="35px" Width="100px" OnClick="HeaderOne_Click" /> <br />
<asp:Button ID="HeaderTwo" class="tool" runat="server" Text="Header 2" Height="35px" Width="100px" OnClick="HeaderTwo_Click" /> <br />
<asp:Button ID="HeaderThree" class="tool" runat="server" Text="Header 3" Height="35px" Width="100px" /><br />
<asp:Button ID="HeaderFour" class="tool" runat="server" Text="Header 4" Height="35px" Width="100px" /><br />
<asp:Button ID="HeaderFive" class="tool" runat="server" Text="Header 5" Height="35px" Width="100px" /><br />
<asp:Button ID="HeaderSix" class="tool" runat="server" Text="Header 6" Height="35px" Width="100px" /><br />
</div>
<div runat="server" class="emailPreview" id="emailPreview">
</div>
C#
protected void HeaderOne_Click(object sender, EventArgs e)
{
emailPreview.Controls.Add(new LiteralControl("<label class='labelHeader1' contentEditable=true>"));
emailPreview.Controls.Add(new LiteralControl("Header 1"));
emailPreview.Controls.Add(new LiteralControl("</label>"));
}
protected void HeaderTwo_Click(object sender, EventArgs e)
{
emailPreview.Controls.Add(new LiteralControl("<label class='labelHeader2' contentEditable=true>"));
emailPreview.Controls.Add(new LiteralControl("Header 2"));
emailPreview.Controls.Add(new LiteralControl("</label>"));
}
CodePudding user response:
On asp.net postback, all of the dynamically added controls disappear. There are two ways to solve this.
First method -
Save a list of dynamically added controls in your Session
,
each render you should check
if (IsPostBack)
and if it is a postback, render all the controls in the list you saved to the session before appending new ones.
Second method - You can bind an onclick event with javascript and add the elements from there. this method will not require a refresh to the page (postback) and will not delete/overwrite the elements you added previously