Creating a style rule on a partial postback using Header.Stylesheet.CreateStyleRule

After implementing an UpdatePanel on my webpage to display different usercontrols, I encountered a problem with adding inline styling dynamically using Header.Stylesheet.CreateStyleRule during partial postbacks. It seems that the styles are not being inserted on partial postbacks since the header is only rendered when the page loads initially.

The methods used to add styling are fetching the styles from a database:

Private Sub InitializeStylesheet(ByVal ButtonId As Integer)
    Dim CSSStylesheet As Stylesheet = StyleBackend.GetStylesheets(ButtonId)
    Dim IdClassList As List(Of StyleIDClass) = StyleBackend.GetStylesheetsStyleIDClass(CSSStylesheet.StylesheetID)
    'Iterates through the cssidclass
    For Each cssidClass In IdClassList
        Dim styleItems As List(Of StyleItem) = StyleBackend.GetStyleItemsByIDorClass(cssidClass.StyleIDClassID)
        Dim cssString As String = Nothing
        For Each StyleItem As StyleItem In styleItems
            cssString += StyleItem.Property & ":" & StyleItem.Value & ";"
        Next
        'Iterates all cssitems which belongs to a cssidclass
        Me.Header.StyleSheet.CreateStyleRule(New CustomStyle(cssString), Nothing, cssidClass.ClassOrID)
        Me.Header.ViewStateMode = UI.ViewStateMode.Disabled
    Next
End Sub

I've searched extensively for a solution but haven't been able to find one.

A reference in msdn confirms the impossibility of achieving what I'm attempting: http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlhead.stylesheet.aspx

Adding styles or style rules programmatically during asynchronous postbacks is not supported. When you add AJAX capabilities to an ASP.NET Web page, asynchronous postbacks update regions of the page without updating the whole page. For more information, see Microsoft Ajax Overview.

If anyone has suggestions or alternative approaches to tackle this issue, I would greatly appreciate it!

Thank you!

Answer №1

If you're looking for a solution, one option is to integrate the styles into your primary stylesheet instead of making dynamic modifications. Even when the styles are driven by data, you can include them in the main page via an HTTP handler if the list isn't excessively long.

Another approach (and potentially more efficient) is to send the style data back to the client as a string and process it there.

To achieve this, you can monitor the EndRequest event on the client script manager:

function endRequest(){
    // analyze the updated DOM
}

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);

You could consider following this sequence:

  • Trigger async postback
  • Output the styles into a hidden field within the UpdatePanel
  • During endRequest, inspect the DOM for the presence of a hidden field with styles (based on naming conventions, data attributes, or ID)
  • Retrieve the values from the hidden field and use JavaScript to apply them as the page's style rules

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

I'm having trouble making Jquery's $.get function work

I've been attempting to use the $.get function to retrieve a response from a PHP script, but I'm not having any luck. Nothing seems to be happening. Here is the jQuery code I am using: $(document).ready( function(){ $('#button').c ...

JavaScript, AJAX rapid iteration

I am working with some ajax code: $(document).ready( function() { $("#button1").click( function() { $.ajax({ type: "POST", url: "update.php", }); }); }); In my HTML code, I have 200 buttons. How can I ...

Making a Cross-Origin Resource Sharing (CORS) request with jQuery utilizing the $

I am currently in the process of building a web application that relies heavily on data from multiple domains. Approximately 90% of the requests made by my application are cross-domain requests. However, I have encountered an issue where I am unable to re ...

The second parameter of the Ajax request is not defined

Having an issue with my Ajax request in Vue.js where the second parameter is logging as undefined in the console. I've been trying to fix this problem but haven't found a solution yet. This is the code snippet for $.ajax(): //$.ajax() to add ag ...

Is it possible to trigger the JavaScript mouseover function following a click event?

Is it possible to call a function on mouse over after the first click event is triggered by the user? <a href="javascript:void(0);" id="digit<?php echo $k;?>" onClick="javascript:return swapClass('<?php echo strtoupper($v);?>',&ap ...

Exploring the world of jQuery's fade transitions paired with the convenience

I've implemented a code snippet for user login via Ajax. However, I'm facing an issue where the fade effects are overlapping with each other due to the quick processing of the request. Despite receiving data to display, I am stuck with just the " ...

beforeSend method in jquery ajax synchronously calling

One of my functions is called: function callAjax(url, data) { $.ajax( { url: url, // same domain data: data, cache: false, async: false, // use sync results beforeSend: function() { // show loading indicator }, ...

Is there a way to bypass strict JSON parsing when using jQuery's .ajax() function?

From jQuery 1.9 onwards, when using dataType: json in a .ajax call and the response body cannot be parsed as JSON, the request will fail silently: The parsing of JSON data is strict; any malformed JSON will be rejected with a parse error. Starting from ...

Exploring jQuery Mobile - What Causes an Empty State?

Using $.mobile.navigate("#test-page", {id:123}) for navigation to a secondary page seems to be successful. The transition between pages is smooth.... but the state remains empty! According to the documentation, the state should contain all necessary info ...

Frostyfire Ajax - Form Sending

I am seeking assistance with ColdFusion. I am interested in utilizing the CF9 ajax library. Currently, I have included <cfajaximport tags="cfform"> in my header and added a form using <cfdiv bind="url:domainchecker.cfm">. However, the entire fo ...

Exception being raised despite handling in JQuery AJAX post request

I am facing an issue with my login JSON service that handles username and password. When I make a call using JQuery 1.10.1 AJAX and input the correct credentials, it functions correctly. However, if I input incorrect credentials, the error function handler ...

Troubleshooting a problem with selecting options in Jquery

Looking for assistance with a jquery script. I have a select dropdown that fetches a list of options via Ajax. When a user clicks on an option, if a certain variable equals 1, an HTML div is added. If the variable changes to another value, the HTML div dis ...

Implementing multiple jQuery Ajax requests in ASP.NET MVC: Efficiently handling concurrent requests

My web page has a tabbed style layout where each tab triggers an Ajax request for their content using jQuery. The backend is ASP.NET MVC running on Visual Studio with the 'ASP.NET Development Server' handling requests. I am encountering the follo ...

Perform a Rails Ajax request to update a like or dislike status

Is there a way to implement like/dislike functionality in my RoR application using Ajax requests? I have integer values for both like and dislike counters. How can I use Ajax requests to increment either the "like" or "dislike" counter in my methods? In ...

When utilizing AJAX, certain web pages may contain a querystring

Encountering an issue with ajax when using query strings. Data can be successfully sent when the page does not have any query string and Info.aspx/Save works perfectly fine. However, when I include query strings and post the same data, it results in a HTTP ...

Clear the modal form in Codeigniter and AJAX upon closing the edit modal

Having an issue with my modal form - when I open the edit modal, the data is fetched and that part works well. However, when I close the modal and try to add a new user, the data is automatically fetched again. Why is this happening? Shouldn't the for ...

The Eclipse Phonegap framework is experiencing difficulty in loading an external string file with the jquery .load function

A basic index.html file has been created to showcase a text string from the test.txt file by utilizing the .load function from the jQuery library. The goal is to insert the textual content into an HTML (div class="konten"). The provided HTML script looks ...

"Executing a jQuery each function without pausing for the completion of an AJAX

When using the .each method in jQuery, it does not wait for the success of an Ajax call. $("img[name='statusIcon']").each(function () { var statusIcon = $(this); statusIcon.attr('src', 'images/spinner.gif'); //loading ...

Significant Google Maps malfunction detected with API V3

Update: Issue resolved, check out my answer below. The scenario: User interacts with a map-image google maps API V3 is loaded using ajax the map is displayed in a dialog window or lightbox What's going on: The map loads and all features are funct ...

Discover the hyperlink and submit it via the form to the designated email address

Is it possible to create a basic HTML form that captures name and email details, then uses jQuery to locate a specific link on the page and includes this link along with the form information in a submission to a web server? From there, a script could send ...