Enhancing the CSS styles of Controls across multiple files using CodeBehind

My AJAX button needs to update some CSS, but I'm facing a challenge. The controls I want to modify are in a separate file and cannot be relocated.

The CSS that needs updating is in the Site.master file within this panel:

<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:UpdatePanel ID="Panel2" runat="server" updatemode="Always">
      <ContentTemplate>
          <div id="updateThis" runat="server"><p>Test text</p></div>
      </ContentTemplate>
</asp:UpdatePanel>

Meanwhile, the button for triggering the update is located in the Items.ascx file:

<asp:UpdateProgress runat="server" ID="PageUpdateProgress">
     <ProgressTemplate>
         <img class="ajax-loader" src="/Images/ajax-loader.gif" alt="Loading..." />
      </ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="Panel3" runat="server" updatemode="Conditional">
     <Triggers>
         <asp:AsyncPostBackTrigger controlid="UpdateButton" eventname="Click" />
     </Triggers>
     <ContentTemplate>

          <asp:Button runat="server" OnClick="UpdateButton"
          OnClientClick="hideButton()" Text="Update" 
          class="update" ID="UpdateButton" name="UpdateButton" 
          type="submit"  ></asp:Button>

     </ContentTemplate>
</asp:UpdatePanel>

This is the method UpdateButton inside Items.ascx.cs:

protected void UpdateButton(object sender, EventArgs e) 
{
    var masterPage = this.Page.Master;
    var updatePanel = masterPage.FindControl("Panel2");

    var div = (HtmlGenericControl)updatePanel.Controls[0].FindControl("updateThis");
    div.Style.Add("color", "#ff0000");  
}

Upon clicking the button, the CSS does not update as expected. Currently, the AJAX UpdateProgress template shows the loading GIF briefly, then the GIF disappears without any color change in the text.

EDIT

To troubleshoot further, consider the following:

THIS WORKS

 protected void UpdateButton(object sender, EventArgs e) 
{
    var masterPage = this.Page.Master;
    var updatePanel = masterPage.FindControl("Panel2");

    var div = (HtmlGenericControl)updatePanel.FindControl("updateThis");
    div.Style.Add("color", "#ff0000");  

    UpdateButton.Text = "Done!";
}

An error was identified where #updateThis was used in FindControl(). Learn from my mistake!

Answer №1

To ensure the div control is visible in code-behind, remember to include the runat="server" attribute:

<div id="updateThis" runat="server"><p>Test text</p></div>

In the event handler, you can optionally remove the reference to Controls[0], although it may still function correctly based on testing:

protected void UpdateButton(object sender, EventArgs e) 
{
    var masterPage = this.Page.Master;
    var updatePanel = masterPage.FindControl("Panel2");

    var div = (HtmlGenericControl)updatePanel.FindControl("updateThis");
    div.Style.Add("color", "#ff0000");  
}

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

Updating expiration on ASP.NET's Session State cookie

Utilizing ASP.NET Session State to manage the logged in users on my website has been helpful. However, one issue I am facing is that the default expiration for ASP.NET session cookies is when the browser closes. I attempted to set my own ASP.NET_SessionI ...

Setting the variable to global does not apply styling to the element

Looking for help with styling an element created using document.createElement("img")? let fireball; //global variable fireball = document.createElement("img") //variable on local fireballArray.push(someFunction(fireball, { src: "img.png&qu ...

Creating a unique HTML contact form in Insightly with properly aligned and spaced fields

Greetings, I must admit that my coding skills are quite limited and I am currently trying to navigate the world of HTML... As I attempted to integrate a basic contact form code from Insightly (provided below/attached), I came across this discussion here ...

Enhancing ag-grid with alternating row group colors following row span

My data structure is shown below: https://i.stack.imgur.com/fy5tn.png The column spanning functionality in ag-grid is working for columns 1 and 2 as expected. However, I am looking to implement alternate row colors based on the values in column 2 (animal ...

Leveraging WCF for an ASP.Net Web Application: Optimal Strategies and Protocols

I am completely new to WCF. Initially, I thought it would operate similarly to regular web services, but now I realize that may not be the case. Our ASP.Net app connects to the WCF service through the internet, with basic security measures and SSL in place ...

Exploring the world of value tracking with JavaScript

on page A test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session")); Response.Redirect("EnterSession.aspx?session=" + e.CommandArgument.ToString()); on page B _gaq.push(['pageTrackerTime._trackEvent', 'categor ...

Sending JSON data back to AJAX

When I utilize AJAX to call a PHP script that returns text in JSON format, my code does not work when I specify dataType as 'json'. However, it works fine when I set it to 'html'. Here is the relevant code: $.ajax({ dataTyp ...

Looking to save the output of a SQL select query in C# variables?

I'm trying to store the return value of the UserId from a SQL query into a variable called Usersid. However, I am having trouble retrieving the value. Just so you know, UserName is text. int usersid; using (SqlConnection connection = new SqlConnectio ...

Design a styled rectangular tab using CSS

Does anyone know of any cool CSS techniques for achieving the tabbed rectangle appearance depicted in the image below? While it's clear that accomplishing this with just one div is not possible, is there a more efficient method than layering one div ...

leveraging jQuery's $.ajax method to fetch information

My go-to method for sending data to a URL has always been $.ajax. However, I recently came across the fact that it's possible to retrieve result data as well. Am I not understanding this correctly? I would appreciate a detailed explanation on how to p ...

Use the angular cli to incorporate the CSS styles found in the node_modules directory

After successfully installing a new library with npm, I now face the challenge of importing the CSS into my project. It seems unwise to directly link to the node_modules folder. Can anyone suggest an easy way to import this CSS into my Angular CLI project? ...

What are some methods for generating stylish code?

Whenever I drag and drop a control into the ascx file, nothing appears in the designer view, and there is no intellisense in the code behind. Are there specific steps to manually create the designer and initialization code, or should I try a different ap ...

Jquery panoramic slider - Dynamically adjusting image width to fit screen size

Currently, I am attempting to implement a popular panning slider called Jquery Panning Slider for a website. The details regarding the markup structure, CSS, and jQuery can be found here: Slider Details. However, I encountered an issue with this slider. ...

Retrieve BD information using AJAX and encountering a null value in the array due to special characters

Hey, I'm using ajax to retrieve an array of data from the database: $.post ( "lib/php/load_food.php", {f:Base64.encode("primeros")}, function(data) { firsts = data; }, "json" ); However, in the 'firsts' array, strings containing accented c ...

Struggling to align text to the far left within a text area using Bootstrap

When I accidentally place my cursor earlier in the text area, it starts writing from that point, leaving some unwanted spaces at the beginning. I prefer it to start from the extreme left, similar to how it behaves in input boxes. Below is the code snippet ...

Differences Among Viewport, Window, and DocumentThese

Examining the code snippet provided below: document.documentElement.clientWidth 1349 document.documentElement.clientHeight 363 window.innerWidth 1366 window.innerHeight 363 window.screen.height 768 window.screen.width 1366 Therefore, my ...

Shopify Inventory Dropdown Tailored to Stock Levels

I'm having an issue with my Shopify store. How can I make sure that the quantity dropdown matches the actual items in stock? For instance, if there are only 3 items available, the maximum value in the quantity dropdown should be set to 3. And if there ...

A guide on producing every character within the UTF-8 charset using .net

Currently, I am assigned with the challenge of generating all characters in the UTF-8 character set to assess how a system manages them. Unfortunately, my knowledge of character encoding is limited. My initial plan was to increment a counter and then conve ...

Adjust size of background image to fit within ie8 window dimensions

Currently, I'm facing an issue where a Drupal 7 module is used to load a background image, but CSS3 resizing is not supported in IE8. background-image: url('image.jpg'); background-size: cover; I have tried conventional methods like placin ...

Initiate the AJAX call when the page is loaded

I want the AJAX request to load automatically when the page loads. Currently, I have to refresh the page for it to be loaded. Here is the updated code snippet: $(document).on("pageinit", "#members", function() { $.ajax({ url: 'data.php', succe ...