You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET中实现网站文本(准)实时更新

Hey there! Let's break down why your current approach isn't working and fix it step by step.

First, why your existing JavaScript isn't auto-clicking the button

The issue with your setInterval line is that you're immediately executing the click() method instead of passing a function reference to run repeatedly. Here's the fix:

// Wrong: runs click() once immediately, not on interval
// var intervalID = setInterval(document.getElementById("Refresher").click(), 50);

// Correct: passes a function to run every X milliseconds
var intervalID = setInterval(function() {
    document.getElementById("Refresher").click();
}, 1000); // Changed to 1000ms (1 second) - 50ms is way too frequent for server requests!

Also, 50 milliseconds is extremely aggressive—this would send 20 requests per second to your server, which will cause performance issues. Stick to at least 1 second (1000ms) or longer depending on how often your data actually changes.

Why server-side timers don't work for this

ASP.NET Web Forms uses a request-response model: once the page is sent to the browser, the server doesn't have a direct connection to push updates to the client. A server-side timer would run on the server, but it can't automatically update the client's page unless you use a mechanism to pull or push data.

Better approaches for real-time/periodic updates

Option 1: Use ASP.NET UpdatePanel + Timer (simplest for Web Forms beginners)

This lets you do partial page updates without full postbacks, using built-in ASP.NET controls:

  1. Wrap your textout Literal and related controls in an UpdatePanel
  2. Add an ASP.NET Timer inside the panel to trigger automatic updates

Here's the modified markup:

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <asp:Button ID="Start" runat="server" Text="Start" OnClick="Program_Start" />
    <input type="Text" name="textin" placeholder="Input" data-toggle="tooltip" id="textin" runat="server" />
    <asp:Button ID="submit_button" runat="server" OnClick="Submit_button" Text="Submit" UseSubmitBehavior="true" />
    <br />

    <!-- Required ScriptManager for UpdatePanel functionality -->
    <asp:ScriptManager runat="server" ID="ScriptManager1"></asp:ScriptManager>
    
    <!-- Partial update panel to refresh only the text output -->
    <asp:UpdatePanel runat="server" ID="UpdatePanel1">
        <ContentTemplate>
            <asp:Literal runat="server" ID="textout" />
            <!-- Hide the refresh button since we'll use the timer -->
            <asp:Button ID="Refresher" runat="server" OnClick="Refresh" Text="Refresh text" Style="display:none;" />
            <!-- Timer triggers the Refresh method every 1 second -->
            <asp:Timer runat="server" ID="UpdateTimer" Interval="1000" OnTick="Refresh"></asp:Timer>
        </ContentTemplate>
    </asp:UpdatePanel>

    <script>
        $(document).ready(function () {
            $(window).keydown(function (event) {
                if (event.keyCode == 13) {
                    event.preventDefault();
                    return false;
                }
            });
        });
    </script>
</asp:Content>

Keep your existing Refresh code-behind method (the one that updates textout with your global string)—the Timer will call this method automatically every second, and the UpdatePanel will only refresh the textout area instead of the whole page.

Option 2: Pure AJAX (more efficient, no postbacks)

If you want to avoid postbacks entirely, you can create a server-side web method and call it directly from JavaScript:

  1. Add a static web method in your code-behind (marked with [WebMethod]):
using System.Web.Services;

public partial class YourPage : System.Web.UI.Page
{
    // Your frequently updated global string
    private static string YourGlobalString = "";

    [WebMethod]
    public static string GetUpdatedText()
    {
        // Return your dynamic global string here
        return YourGlobalString;
    }

    // Your existing Program_Start, Submit_button, Refresh methods...
}
  1. Update your front-end JavaScript to fetch data periodically via AJAX:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <asp:Button ID="Start" runat="server" Text="Start" OnClick="Program_Start" />
    <input type="Text" name="textin" placeholder="Input" data-toggle="tooltip" id="textin" runat="server" />
    <asp:Button ID="submit_button" runat="server" OnClick="Submit_button" Text="Submit" UseSubmitBehavior="true" />
    <br />
    <asp:Literal runat="server" ID="textout" />

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script>
        $(document).ready(function () {
            $(window).keydown(function (event) {
                if (event.keyCode == 13) {
                    event.preventDefault();
                    return false;
                }
            });

            // Fetch updated text every 1 second
            setInterval(function() {
                $.ajax({
                    type: "POST",
                    url: "YourPage.aspx/GetUpdatedText", // Replace with your actual page name
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(response) {
                        // Update the literal with the new text
                        $("#textout").text(response.d);
                    },
                    error: function(xhr, status, error) {
                        console.error("Error fetching data:", error);
                    }
                });
            }, 1000);
        });
    </script>
</asp:Content>

This approach is more efficient because it only sends the necessary data (not the whole page) between client and server.

Final Notes

  • If you need true real-time updates (instant pushes when data changes, not just periodic checks), look into ASP.NET SignalR—it lets the server send updates to clients automatically without repeated polling.
  • Always test your interval duration—don't make it shorter than necessary, as it can strain your server resources.

内容的提问来源于stack exchange,提问作者Sorpl3x

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:12:55