简体   繁体   中英

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

I am currently in the process of creating an asp.net webforms site in c#.

My goal with this website is to be able to receive mqtt messages from a mqtt broker that I currently have running, and disply them on a simple website.

I currently have the communication up and running and can subscribe and receive messages just as I wish, but my problem is that after receiving the messages in my code-behind, I am not able to dynamically display them in my aspx! I am currently trying to display a value in an asp:label, and every time I receive a new value I would like to update the label-text to reflect this.

Again my code-behind is working as intended, but my problem seems to be that the messages from my mqtt broker is not causing a page-load or postback, which means that my aspx are not getting refreshed. I have tried to solve this using JavaScript, but this doesn't seem to work! Here is a simplified version of my code:

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();
        }
    }
}

I am not sure if my JavaScript is relevant, but I wrote it as an attempted workaround to my problem (which is that the label-text is not getting updated when I receive new messages from my broker).

It seems to me that the Broker is sending messages to the server of device A and the client of your page is on machine B and you are trying to synchronize, if this is the case, update a database on the server and use something similar with my example.

In my example i will focus on "I have tried to solve this using javascript, but this doesnt seem to work!".

Either way, you have chosen the wrong technology to do this, WebForms will give you a lot of headache.

Use Asp.Net MVC ... will be much easier.

Page

<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>

Code-Behind

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM