【问题标题】:Dynamically change label text in aspx page without postback or page-load动态更改 aspx 页面中的标签文本,无需回发或页面加载
【发布时间】: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 中来完全避免我的问题(因为实际上我计划实施无论如何,数据库,但我只是想等到我有一个工作的概念证明)。?

标签: c# asp.net webforms mqtt


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多