簡體   English   中英

動態更改aspx頁面中的標簽文本,而無需回發或頁面加載

[英]Dynamically change label text in aspx page without postback or page-load

我目前正在用C#創建一個asp.net Webforms網站。

我在此網站上的目標是能夠從我當前運行的mqtt代理接收mqtt消息,並將其顯示在一個簡單的網站上。

我目前可以正常進行通訊,並且可以按我的意願訂閱和接收消息,但是我的問題是,在收到我的代碼隱藏消息后,我無法在aspx中動態顯示它們! 我目前正在嘗試在asp:label中顯示一個值,並且每當我收到一個新值時,我都希望更新標簽文本以反映此情況。

再次,我的后台代碼按預期工作,但是我的問題似乎是來自我的mqtt代理的消息沒有引起頁面加載或回發,這意味着我的aspx沒有得到刷新。 我嘗試使用JavaScript解決此問題,但這似乎不起作用! 這是我的代碼的簡化版本:

Aspx:

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

<head runat="server">
<script type="text/javascript">
    var jsVariable1;
    function GetValues(){                        
        var someVar1 = "<%=Variable1 %>";
        if(someVar1 != null && someVar1 != jsVariable1){

        jsVariable1 == someVar1;
        $('#Label1').innerHTML = "Variable 1 =<br/>" + jsVariable1;
        }
    setTimeout(GetValues, 5000);
    }
    GetValues();
</script>
</head>

<body>
<form id="form1" runat="server">

<div class="container" id="container">
    <img src="/Images/TestImage.jpg" style="width:100%;" />

  <div class="position1">
      <asp:Label ID="Label1" runat="server" Text="Var1: <br/> Value"></asp:Label>
  </div>

</div>
    </form>
</body>

.cs:

namespace proof_of_concept
{
public partial class WebForm1 : System.Web.UI.Page
{
    private static MqttClient myClient;
    public String Variable1 = "No data yet";

    protected void Page_Load(object sender, EventArgs e)
    {
        Page.DataBind();

        if (!IsPostBack)
        {
            //Initialize connection to the mqtt broker (with a hardcoded URL)
            myClient = new MqttClient("myBrokerurl", 1883, false, null, null, 0, null, null);

            //Connect to the broker with an autogenerated User-ID
            myClient.Connect(Guid.NewGuid().ToString());

            //Check if the connection was established
            Debug.WriteLine("Client connected: " + myClient.IsConnected);

            //Subscribe to a topic at the broker (Again in this example the topic has been hardcoded)
            myClient.Subscribe(new string[] { "mySubscribedTopic/#" },
            new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });

            //Sets up an eventhandler for received messages to the subscribed topic(s)
            myClient.MqttMsgPublishReceived += myClient_MqttMsgPublishReceived;
        }

    }

    protected void myClient_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
    {
        //Check if a message was received
        Debug.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);

        variableSelector(e.Topic, Encoding.UTF8.GetString(e.Message));
    }

    protected void variableSelector(String topicString, String messageString)
    {
        if (topicString.Contains("var1") == true)
        {
            Variable1 = messageString;

            //Databinding here was a test that didnt seem to do anything
            Page.DataBind();
        }
    }
}

我不確定我的JavaScript是否相關,但是我將其編寫為解決我的問題的變通辦法(這是當我從經紀人處收到新消息時,標簽文本沒有得到更新)。

在我看來,代理正在將消息發送到設備A的服務器,並且頁面的客戶端在計算機B上,並且您嘗試進行同步(如果是這種情況),請更新服務器上的數據庫並使用與我的例子。

在我的示例中,我將重點介紹“我試圖使用javascript解決此問題,但這似乎不起作用!”。

無論哪種方式,您都選擇了錯誤的技術來執行此操作,WebForms會讓您頭疼。

使用Asp.Net MVC ...會容易得多。

<form id="form1" runat="server">
    <asp:ScriptManager ID="MyScriptManager" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="MyUpdatePanel" runat="server">
        <ContentTemplate>
            <asp:Label ID="MyLabel" runat="server"> Postback number <%= Counter %></asp:Label>
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

代碼隱藏

public partial class MyPage: System.Web.UI.Page
{
    protected int Counter { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            // MyUpdatePanel will perform a async post-back every 1000 milliseconds

            int _newCounter;
            var newCount = Request.Form["__EVENTARGUMENT"];
            if (newCount != null)
            {
                if (int.TryParse(newCount, out _newCounter))
                {
                    Counter = _newCounter;
                }
            }
            return;
        }

        // Loading javascript that will trigger the postback

        var _pageType = this.GetType();
        var script =
            string.Concat(
                "var counter = 0;",
                "setInterval(function() { ",
                "__doPostBack('", MyUpdatePanel.UniqueID, "', counter);",
                "counter++; }, 1000);");
        ClientScript.RegisterStartupScript(_pageType, "AutoPostBackScript", script, true);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM