简体   繁体   English

动态更改aspx页面中的标签文本,而无需回发或页面加载

[英]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#. 我目前正在用C#创建一个asp.net Webforms网站。

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. 我在此网站上的目标是能够从我当前运行的mqtt代理接收mqtt消息,并将其显示在一个简单的网站上。

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! 我目前可以正常进行通讯,并且可以按我的意愿订阅和接收消息,但是我的问题是,在收到我的代码隐藏消息后,我无法在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. 我目前正在尝试在asp:label中显示一个值,并且每当我收到一个新值时,我都希望更新标签文本以反映此情况。

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. 再次,我的后台代码按预期工作,但是我的问题似乎是来自我的mqtt代理的消息没有引起页面加载或回发,这意味着我的aspx没有得到刷新。 I have tried to solve this using JavaScript, but this doesn't seem to work! 我尝试使用JavaScript解决此问题,但这似乎不起作用! Here is a simplified version of my code: 这是我的代码的简化版本:

Aspx: 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: .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). 我不确定我的JavaScript是否相关,但是我将其编写为解决我的问题的变通办法(这是当我从经纪人处收到新消息时,标签文本没有得到更新)。

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. 在我看来,代理正在将消息发送到设备A的服务器,并且页面的客户端在计算机B上,并且您尝试进行同步(如果是这种情况),请更新服务器上的数据库并使用与我的例子。

In my example i will focus on "I have tried to solve this using javascript, but this doesnt seem to work!". 在我的示例中,我将重点介绍“我试图使用javascript解决此问题,但这似乎不起作用!”。

Either way, you have chosen the wrong technology to do this, WebForms will give you a lot of headache. 无论哪种方式,您都选择了错误的技术来执行此操作,WebForms会让您头疼。

Use Asp.Net MVC ... will be much easier. 使用Asp.Net MVC ...会容易得多。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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