Checkbox selection not retained after update panel triggers

I am facing an issue with a div, id = campaignDiv, which loads its content dynamically.

The content consists of checkboxes.

There is an update panel that triggers every 30 seconds.

The Challenge

Whenever the update panel triggers, the checkboxes reset to their default state of being unselected.

I am willing to provide all my code, which is quite simple. You can simply copy and paste it into Visual Studio for it to work.

WebForm4.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="TestDropdownChecklist.WebForm4" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="StyleSheet1.css"/>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick">
                </asp:Timer>

                <div id="campaignDiv" runat="server">
                    <ul>
                    </ul>
                </div>

            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
            </Triggers>
        </asp:UpdatePanel>
    </form>
</body>
</html>

WebForm4.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestDropdownChecklist
{
    public partial class WebForm4 : System.Web.UI.Page
    {
        private string CreateLiCheckbox(string checkBoxText)
        {
            return string.Format("<li><span class=\"textDropdown\">{0}</span><input runat=\"server\" id=\"{1}\" value=\"{0}\" type=\"checkbox\"><label for=\"{1}\"></label></li>", checkBoxText, checkBoxText + "dropdownID");
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            int refreshtime = 30000;
            Timer1.Interval = refreshtime;
            if (!IsPostBack)
            {
                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;
            }
            else
            {

            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {


        }

    }
}

StyleSheet1.css

#DropdownSeviceLink {
    float: right;
    margin-right: 10px;
}

a#DropdownServiceLink:visited {
    color: inherit;
}

#campaignDiv {
    background-color: #374954;
    width: 200px;
    height: 170px;
    padding-bottom: 10px;
    position: absolute;
    top: 40px;
    right: 0;
}

    #campaignDiv ul {
        color: #fff;
        list-style: none;
        overflow: auto;
        padding-left: 5px;
        height:100%;
    }

    #campaignDiv input[type=checkbox] {
        visibility: hidden;
    }

        #campaignDiv input[type=checkbox]:checked + label {
            left: 60px;
            background: #26ca28;
        }

    #campaignDiv li {
        width: 100px; /*120*/
        height: 25px; /*40*/
        background: #333;
        margin: 13px 0px; /*20px 60px*/
        border-radius: 50px;
        position: relative;
    }

        #campaignDiv li:before {
            content: 'On';
            position: absolute;
            top: 4px; /*12*/
            left: 13px;
            height: 2px;
            color: #26ca28;
            font-size: 16px;
        }

        #campaignDiv li:after {
            content: 'Off';
            position: absolute;
            top: 4px; /*12*/
            left: 71px; /*84*/
            height: 2px;
            color: #111;
            font-size: 16px;
        }

        #campaignDiv li label {
            display: block;
            width: 36px; /*52*/
            height: 18px; /*22*/
            border-radius: 50px;
            -webkit-transition: all .5s ease;
            -moz-transition: all .5s ease;
            -o-transition: all .5s ease;
            -ms-transition: all .5s ease;
            transition: all .5s ease;
            cursor: pointer;
            position: absolute;
            top: 4px; /*9*/
            z-index: 1;
            left: 12px;
            background: #ddd;
        }





.textDropdown {
    margin:0px;
    padding:0px;
    margin-left: 110px;

}

It has been suggested on the internet that I may need to add the checkboxes to my update panel using this format:

UpdatePanel1.ContentTemplateContainer.Controls.Add(dynamic controls);
. However, my issue arises as the checkbox in my case is a string and not an object. Is there another way I should be adding the checkboxes dynamically?

Edit

After researching online, I found a solution that works, although I still have one unresolved issue. Your help is greatly appreciated.

Edit for the great user Schadensbegrenzer

Your answer was helpful and worked well, thank you so much! However, I still have an unresolved issue. Can you please modify your answer so that the rendered HTML looks like this:

<div id = campaignDiv>
    <ul>
              <li>
                        Checkbox here
              </li>
    </ul>
</div>

In your code, I made the campaginDiv the id of asp:CheckBoxList

Answer №1

Initially, including runat="server" in your html string serves no purpose in this context since it won't be processed by the server and will be transmitted to the client intact.

In addition, your update panel will consistently display the same content because it is refilled from the ViewState. If you disable the view state of the update panel, on the subsequent refresh it will display an empty panel (as there's no view state to draw from).

So, what should you do in this situation? You must reload the contents of the update panel upon postback and manually extract the client state.

If the size of the view state is a concern for you, you can take the following steps:

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

Answer №2

For better code organization, here is my revised suggestion for the checkboxlist implementation. I trust this meets your requirements.

.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 approach ensures that your checkboxes remain checked.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent scrolling with absolute positioning

Here's a snippet of my HTML pseudocode: <div> <VideoAnimation /> <div className="under-animation"> // a lot of content goes here </div> </div> The issue arises from using absolute positioning on th ...

Apply a unique font to the gridview that is not universally available on all systems

Can I use a custom font for my gridview that is accessible to all users, even if it doesn't exist in all systems? Is there a way to include the font in the project folder so that it can be viewed by everyone? ...

After reducing the size of the table, the data spills over

Hey there, amazing individuals of the internet! Hope you're all doing well today. I've encountered a rather perplexing issue that's got me stumped. So, here's the situation - I have this table full of data and I want it to initially be ...

Fixing a JavaScript Issue with Updating Div Class Content

When attempting to replace HTML content within a specific class, everything seems to work fine with simple code like <p>0</p>. However, when trying to input more complex code such as: $('.festi-cart-menu-item').html('<a id=" ...

I am having trouble connecting the local JSON file to the website

I'm working on a school project where I need to link a local JSON data file to an HTTP webpage to retrieve the data, but I'm having trouble getting the results. The code below is the JSON local code that I want to integrate into the webpage inste ...

What could be causing my function to not register with my EventListener?

I'm attempting to perform an action when I click on an element. I have added an eventListener to change the value of a variable upon clicking on that element. However, the eventListener is not working as expected. When I debug the code, it seems like ...

Is it possible to determine if certain file metadata is set to read-only?

By using the code snippet below, I am able to save certain EXIF properties into a jpg picture. var propertyToSave = new List<KeyValuePair<string, object>>() { new KeyValuePair<string, object>("System.Photo.LensManufacturer", "Canon" ...

Identifying modifications to the content of a text area

Is there a way to determine if the value in my textareaId has changed due to JavaScript? For example: $("#buttonID").on("click, function(){ $("#textareaID").val("lorem ipsum"); }); $("#textareaID").change(function(){ //not working }); $ ...

Having difficulty incorporating custom JavaScript files into a testing framework

I am facing a unique challenge while integrating the Page Object design pattern into my test suite using selenium-webdriver and node.js. The first page object, pageObject/admin/login/index.js, works seamlessly. It contains selectors and methods to fill ou ...

Using setTimeout or setInterval for polling in JavaScript can cause the browser to freeze due to its asynchronous

In order to receive newly created data records, I have developed a polling script. My goal is to schedule the call to happen every N seconds. I experimented with both setTimeout() and setInterval() functions to run the polling task asynchronously. However ...

Show information - press the button on the current PHP page

After successfully reading files via PHP from a directory and dynamically creating a drop-down menu to view the file content, I have a query. Is there a way to display the text files' content on the same page without calling another PHP page? I know t ...

trouble concerning the responsiveness of a jQuery popup

Hello, I am trying to create a responsive login popup using jQuery but have been struggling for a week. Below is the code snippet that I have been working on. Any help or guidance would be greatly appreciated. //scriptLogin.js archive $(document).ready ...

Leveraging retrieved API data to generate numerous components

Hey there! I'm new to JavaScript and I'm working on creating a todo list with fake ToDos from jsonplaceholder using Fetch. My goal is to fetch five different ToDos and display them in separate list items within my list. However, I'm encounte ...

Dividing Text within a Stored Function

I need assistance in utilizing MYSQL Stored Procedure to split the provided input string for data insertion into a table. The words in the input must be grouped accordingly. Input: string strTest = AAA-1111,AAA-666,SMT-QWQE,SMT-TTTR Desired output ...

Create a Boxplot chart using Chart.js that dynamically adjusts the minimum and maximum values to allow for additional space on either

I am utilizing chartjs v2.9 for creating a boxplot and my code structure is as follows: function generateRandomValues(count, minimum, maximum) { const difference = maximum - minimum; return Array.from({length: count}).map(() => Math.random() * ...

The custom validator for the checkbox in the gridview ensures that only one row is flagged as invalid

In a gridview, each row has checkboxes for selecting items (1 to 4) and a "none" checkbox. I want to display an error if the "none" checkbox is selected along with any other item in the row. I'm using a custom validator, but it only works for the firs ...

Is dynamic data supported by Next.js SSG?

I'm currently developing a web application with Next.js and I need clarification on how Static generated sites work. My project is a blog that necessitates a unique path for each blog entry in the database. If I were to statically generate my web appl ...

What is the most effective method for incorporating multiple simultaneous Ajax requests into a single view or page?

Within a data-focused web application, I have multiple razor views containing tables generated using tabulator and updated through self-calling ajax functions on intervals. Typically, these views consist of no more than three tables each with fast network ...

Consistent Failure: jQuery File Upload consistently aborts with the error message 'File upload aborted'

I'm currently utilizing the Blueimp File Upload Plugin to facilitate file uploads to a remote server. The HTML code snippet for the file upload input is as follows: <input id="fileupload" type="file" name="files[]" data-url="http://my-server-ip/u ...

`How to utilize the spread operator in Angular 4 to push an object to a specific length`

One issue I'm facing is trying to push an object onto a specific index position in an array, but it's getting pushed to the end of the array instead. this.tradingPartner = new TradingPartnerModel(); this.tradingPartners = [...this.tradingPartner ...