动态更改aspx页面中的标签文本,而无需回发或页面加载 [英] Dynamically change label text in aspx page without postback or page-load

查看:127
本文介绍了动态更改aspx页面中的标签文本,而无需回发或页面加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我在此网站上的目标是能够从我当前运行的mqtt代理接收mqtt消息,并将其显示在一个简单的网站上.

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.

我目前可以正常运行通讯,并且可以按照我的意愿订阅和接收消息,但是我的问题是,在我的代码隐藏中接收到消息之后,我无法在aspx中动态显示它们!我目前正在尝试在asp:label中显示一个值,并且每次收到新值时,我都希望更新标签文本以反映此情况.

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.

我的后台代码再次按预期工作,但是我的问题似乎是来自我的mqtt代理的消息没有引起页面加载或回发,这意味着我的aspx未被刷新.我尝试使用JavaScript解决此问题,但这似乎不起作用!这是我的代码的简化版本:

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

我不确定我的JavaScript是否相关,但是我将其写为解决问题的尝试方法(这是当我从经纪人收到新消息时,标签文本没有得到更新).

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

推荐答案

在我看来,代理正在将消息发送到设备A的服务器,并且页面的客户端在计算机B上,并且您正在尝试进行同步,如果是这种情况,请更新服务器上的数据库,并使用与我的示例类似的内容.

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.

在我的示例中,我将重点介绍我尝试使用javascript解决此问题,但这似乎不起作用!".

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

无论哪种方式,您都选择了错误的技术来做到这一点,WebForms会让您很头疼.

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

使用Asp.Net MVC ...将更加容易.

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

页面

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

这篇关于动态更改aspx页面中的标签文本,而无需回发或页面加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆