如何以 10 秒的间隔在 mvc razor 页面中使用 jQuery 调用方法并将输出附加到 html

How to call method using jQuery in mvc razor page at 10 sec interval and append output to html

下面的代码从 iot hub 中读取一条一条消息。

  private async void MonitorEventHubAsync(DateTime startTime, CancellationToken ct, string consumerGroupName)
    {
        EventHubClient eventHubClient = null;
        EventHubReceiver eventHubReceiver = null;

        try
        {
            string mesageData = string.Empty;
            int eventHubPartitionsCount;

            string selectedDevice = "";
            eventHubClient = EventHubClient.CreateFromConnectionString("activeIoTHubConnectionString", "messages/events");
            mesageData = "Receiving events...\r\n";
            eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition = EventHubPartitionKeyResolver.ResolveToPartition(selectedDevice, eventHubPartitionsCount);
            eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime);

            //receive the events from startTime until current time in a single call and process them
            while (true)
            {
                var eventData = eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1)).Result;

                if (eventData != null)
                {
                    var data = Encoding.UTF8.GetString(eventData.GetBytes());
                    var enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime();
                    var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();

                    if (string.CompareOrdinal(selectedDevice.ToUpper(), connectionDeviceId.ToUpper()) == 0)
                    {
                        mesageData += $"{enqueuedTime}> Device: [{connectionDeviceId}], Data:[{data}]";

                        if (eventData.Properties.Count > 0)
                        {
                            mesageData += "Properties:\r\n";
                            foreach (var property in eventData.Properties)
                            {
                                mesageData += $"'{property.Key}': '{property.Value}'\r\n";
                            }
                        }

                        mesageData += "\r\n";
                    }
                }
            }

        }
        catch (Exception ex)
        {

        }
    }

我想使用上面的代码在 mvc cshtml 页面上一条一条地显示消息,我该怎么做?

我可以使用如下的一种方法:

  1. 在 cshtml 中

      <p id="pValue"></p>
    
  2. 在脚本中

        var someRootPath = "@Url.Content("~")";
          (function randomGenerator() {
             $.ajax({
                 url: someRootPath + 'Home/GetValue',
                 success: function (data) {
                     $('#pValue').html(data.someValue);
                 },
                 complete: function () {
                     setTimeout(randomGenerator, 1000);
                 }
             });
         })();
    
  3. 控制器

     [HttpGet]
     public JsonResult GetValue()
     {
         return Json( // call winform method which gives message data);
     }
    

像这样

var someRootPath = "@Url.Content("~")";

$(function(){

    randomGenerator();
    setTimeout(randomGenerator, 1000);

});
function randomGenerator() {
    $.ajax({
        url: someRootPath + 'Home/GetValue',
        success: function (data) {
            $('#pValue').html(data.someValue);
        }
    });
}