Run the code-behind method each time the DIV is loaded on the page (using ASP, ascx, and ascx

A unique concept behind this particular div is that it contains a quote from a customer fetched from the server by means of a random function call. Every few seconds, a jQuery script runs to smoothly fade out the current quote and display another one in its place.

The following code snippet represents my Div implementation in my .ascx file:

<div class="testimonial" ID="Fader" onload="runTestimonial">

<q>"<asp:Literal runat="server" ID="Quote"></asp:Literal>"</q>

</div>

Code Behind (.ascx.cs):

protected void runTestimonial(object sender, EventArgs e)
{ --lots 'o code--

Partnership partnership = Partnership.GetRandomTestimonial(cmPage.CMPageId);
            if (partnership != null)
            {
                Quote.Text = partnership.Testimonial;
                Visible = true;
            }
}

Utilizing the following jQuery code:

setInterval(
    (function () {
        $('#Fader').fadeOut('slow', function () {
            setTimeout(function () { $('#Fader').load().fadeIn('slow'); }, 300);
        });
    })
    , (200))

The jQuery functionality appears to be properly set up as it interacts with the div's Fader ID to manage the fading and loading effect.

In the past, the div would fetch the quote using a Page_Load method of similar structure which worked seamlessly. The recent modification requires the retrieval to occur not on initial page load, but with the help of jQuery refresh events.

Currently, the div fades in and out as intended, however, it displays as blank indicating an issue with rendering the ASP content. Executing the runTestimonial function seems to be the problem area, possibly due to an incorrect invocation within the jQuery context.

Struggling with C#, jQuery, ASP, or code-behind procedures? Seeking assistance!

Answer №1

To implement this functionality using jQuery and WebMethod, follow these steps:

1) Convert your existing runTestimonial() function into a WebMethod that returns a random testimonial as a string. Update the function signature as follows:

[WebMethod]
public static string runTestimonial()
{
    return randomTestimonial; // add your code here
}

2) Include the jQuery library in the head section of your file.

<script src="http://code.jquery.com/jquery-latest.js"></script>

3) Create a new function to make an ajax call to your WebMethod.

function getTestimonial()
{
   $.ajax({
     type: "POST",
     url: "Default.aspx/runTestimonial",
     data: "{}",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function(msg) {
       $("#Fader").html(msg); // append response to the div
     }
   });
}

4) Remove the onload attribute from your div in the markup, since it is not a server control. Simply define the div like this:

<div class="testimonial" ID="Fader"></div>

5) Finally, ensure to call the getTestimonial() function within your setInterval method to initiate the process.

Note that the [WebMethod] attribute is part of the System.Web.Services library, so remember to include it at the beginning of your page:

using System.Web.Services;

By following these steps, your setup should be ready to go.

Answer №2

In a nutshell, C# operates on the server side, which means that the method runTestimonial cannot be found on the client's browser. To solve this issue, you should develop a JavaScript function that utilizes jQuery to communicate with the server through an ajax request. I recommend exploring tutorials on jQuery/ajax/ASP.Net to enhance your understanding. It appears that you may be lacking some foundational knowledge in this area. I hope this information proves useful!

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

What is the best way to assign a value from server-side code to an asp.net TextBox with TextMode set to "Date"?

Currently working on a demo application to familiarize myself with the new HTML5 input types, such as Date and email, implemented in the asp.net textbox control. On my test page, I aim to exhibit server-side date field information using an asp:TextBox wit ...

Having trouble getting the CSS class to work in MVC4 with jQuery implementation

I recently created a view page where I implemented some jQuery code: <script type="text/javascript"> $(document).ready(function () { var hdrname = $('#headername').text(); alert(hdrname); if (hdrname == "Pending Assignment") { ...

What could be the source of this margin or spacing?

Within this test, I have noticed that there are 2 inline flex containers. Specifically, I am referring to the test scenario that states Next The flex containers are laid out inline. Despite the fact that there is some space between the containers, upon in ...

How can we consistently center a window using a grid layout while keeping the elements off-center?

I'm trying to achieve a grid container that always stays centered while the elements with fixed width float left, even when breaking. In my example, the alignment is off and not centered. Can this be fixed with CSS only or do I need to use JavaScript? ...

Animating the display and concealment of a Ui Bootstrap alert within an AngularJS modal window

Trying to create a dynamic animation for an ng-hide feature used on a Ui Bootstrap alert button within a Ui Bootstrap Modal is proving to be quite challenging. The goal is to have the alert slide in and out while simultaneously fading in and out. Although ...

In Bootstrap 4, IE 11 struggles with images overflowing within a d-flex div containing an img tag

My webpage utilizes the bootstrap 4 grid system and appears correctly on most browsers, except for IE 11. If you check out this snippet on jsfiddle in IE 11, you'll notice that the image gets stretched inside a d-flex container. How can I resolve this ...

Experiencing difficulty retrieving the ID of a modal popup in JavaScript

I am facing an issue with my update panel and modal popup. The modal popup is located outside of the update panel, and when I try to access it from JavaScript using document.getElementById, $get or $find, it returns null as it cannot find the modal popup. ...

How can I move Bootstrap 5 navbar list items to the right side?

I'm struggling to position the signup and login links on the right side of the page. I've tried using mr-auto, ml-auto, and justify-content-end but none of them seem to be working. <nav class="navbar navbar-expand-lg navbar-light"&g ...

What specific CSS attribute changes when an element is faded out using jQuery's FadeOut method?

When we make an element fade in or out, which specific CSS property is being altered? Is it the visibility attribute, or the display property? I am hoping to create a code snippet with an if statement condition that reads (in pseudo code): if the div is ...

Locate every div element that contains a span id matching any word in a specified list

I'm attempting to create a script that will add a class based on whether or not a list item's span id contains certain words from a list. The list follows this structure: <div id="main_list"> <li class> <a data-item_ ...

Obtaining Session State in Global.asax

This error message is popping up: "Session state is not available in this context." I'm a beginner programmer and I'm wondering how to access Session in Global.asax Here's the code snippet from my Global.asax file: public class Global : S ...

Preventing functionality with Jquery hashtag in the URL

My Jquery code successfully shows and hides divs with a button click, but it seems to only work for the first two clicks. After that, a hashtag appears in the URL and the script stops functioning. I attempted to add `e.preventDefault()` at the beginning ...

What is the best way to display a Bootstrap pop-up and then automatically hide it after a few seconds

Does anyone know how to display a Bootstrap popup when the page loads and automatically hide it after 3 seconds? I found an example online but I'm unsure how to adapt the code for my specific needs. <button type="button" class="btn btn-primary" da ...

The barely noticeable difference of 1 pixel in the link between Chrome and Firefox

Hello there, I need some advice on how to adjust a one-pixel difference between Chrome and Firefox. The menu links appear correctly in Chrome, but in Firefox, they are 1px smaller than they should be. Below is the CSS code: ul#menu { padding: 0 0 2px ...

Client Certification for Secure Web Authentication

As I work on authenticating the login of a web app, I am considering three key elements: Userid for the web app Password for the web app Client Certificates installed on the user's PC. Usually, a client or machine certificate is stored as a lengthy ...

The min-height property in CSS appears to be ineffective on Jelly Bean

In my current project developing an Android application, I have incorporated Webviews in certain activities and fragments. However, I encountered a perplexing issue when running the app on Jelly Bean (api 16 and 18) emulator - the css property min-height ...

The alignment of Material-UI Typography in AppBar appears to be off

Having trouble centering text in an AppBar? You're not alone. Despite trying various methods like using Typography element, align="center", textAlign="center", and style={{ align: "center" }}, among others: class CustomApp extends React.Component { ...

Collapsing Bootstrap menu bar causing logo overlap

When the navbar collapses (when it shows the toggle icon), the menu items (home, services, portfolio, about, contact) overlap with the logo. If I remove the position:absolute from the logo (navbar-brand), the menu appears in the center. Is there a way to h ...

New issue discovered when attempting to integrate WFRESH with WS-Federation through ADFS

My application uses ADFS 2 for authentication via WS-Federation. Upon receiving the response from ADFS, I search for a specific claim to authorize users into the application. To enhance this process, I want to redirect users back to ADFS if they authentica ...

Implement a full-width dropdown menu with Bootstrap 4

Hey guys, I'm having a real head-scratcher here. I've created a dropdown menu using Bootstrap 4, but I'm having trouble making it responsive for mobile screens. I've tried using media queries to make the dropdown menu occupy 100% width ...