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

时间:2017-11-12 11:09:23

标签: c# asp.net webforms mqtt

我目前正在使用c#创建一个asp.net webforms网站。

我在这个网站上的目标是能够从我目前运行的mqtt代理接收mqtt消息,并在一个简单的网站上显示它们。

我目前正在启动和运行通信,可以按照我的意愿订阅和接收消息,但我的问题是在我的代码隐藏中收到消息后,我无法在我的aspx中动态显示它们!我目前正在尝试在asp:标签中显示一个值,每次收到新值时,我都想更新标签文本以反映这一点。

我的代码隐藏再次按预期工作,但我的问题似乎是来自我的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是否相关,但我把它写成了我的问题的尝试解决方法(当我从我的经纪人收到新消息时,标签文本没有得到更新)。

1 个答案:

答案 0 :(得分:0)

在我看来,Broker正在向设备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);
    }
}