I have an div id = campaignDiv
and I load its content dynamically
The content is checkboxes .
I have an update panel that fires every 30 seconds.
First off, adding runat="server"
to your html string is meaningless here, as it will not be processed by the server and will be sent to the client as is.
Now, your update panel will always emit the same content because its repopulated from the ViewState
, if you disable the update panel view state, on the next refresh it will return an empty panel (there is no view state to read from)
So what to do here! You need to refresh the update panel contents on post back, and manually read the client state.
If view state size does concern you, then do the following:
public partial class WebForm4 : System.Web.UI.Page
{
private string CreateLiCheckbox(string checkBoxText)
{
var checkState = !string.IsNullOrEmpty(Request.Form[string.Format("chk_{0}", checkBoxText)]) ? "checked=\"checked\"" : "";
return string.Format("<li><span class=\"textDropdown\">{0}</span><input id=\"{1}\" name=\"chk_{0}\" value=\"{0}\" type=\"checkbox\" {2}><label for=\"{1}\"></label></li>",
checkBoxText,
checkBoxText + "dropdownID",
checkState);
}
protected void Page_Load(object sender, EventArgs e)
{
int refreshtime = 5000;
Timer1.Interval = refreshtime;
if (!IsPostBack)
PopulateCheckboxes();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
PopulateCheckboxes();
}
private void PopulateCheckboxes()
{
string[] comps = new string[] { "default", "sales", "direct" };
string html = "<ul>";
for (int i = 0; i < comps.Count(); i++)
{
html = html + CreateLiCheckbox(comps[i]);
}
html = html + "</ul>";
campaignDiv.InnerHtml = html;
}
}
To have more space for code here is my suggestion for the checkboxlist again. I hope it's that what you are asking for.
.aspx
<asp:UpdatePanel ID="upStuff" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div id="campaignDiv">
<asp:CheckBoxList runat="server" RepeatLayout="UnorderedList" ID="myCheckboxList" TextAlign="Left">
</div>
</asp:CheckBoxList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick"/>
</Triggers>
</asp:UpdatePanel>
.aspx.cs
if (!IsPostBack)
{
var comps = new[] { "default", "sales", "direct" };
for (int i = 0; i < comps.Count(); i++)
{
myCheckboxList.Items.Add(new ListItem{Text = comps[i]});
}
}
This way it will keep your checkbox checked