【发布时间】:2017-11-12 11:09:22
【问题描述】:
我目前正在用 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 是否相关,但我写它是为了解决我的问题(即当我从代理收到新消息时标签文本没有更新)。
【问题讨论】:
-
嗯,我想知道是否可以通过首先将我的 mqtt 值发送到数据库然后将它们从那里加载到 .aspx 中来完全避免我的问题(因为实际上我计划实施无论如何,数据库,但我只是想等到我有一个工作的概念证明)。?