How to display different values ​​without refreshing MVC C # page

I have a method that iterates over a list of values, which I would like to do when I open a page to see the values ​​change without updating the current view. I tried something like the code below.

public static int myValueReader { get; set; } public static void ValueGenerator() { foreach (var item in myList) { myValue = item; Thread.Sleep(1000); } } 

In fact, I want him to read these values, even if I close the form. I suppose I will need to assign a task for this, but I wandered if there is a better way to do this, since this is an MVC application?

+6
source share
2 answers

Here is another way to do this:

  • use AJAX and setTimeout
  • declare one action in your controller (this will return your different values)
  • an integer in your ViewBag , some like: ViewBag.totalItems

Declare an action in the controller: This is important because it will be your connection to your database or data. This action will receive itemIndex and return this item. Something like that:

 [HttpPost] public JsonResult GetItem(int index) { return Json(myList.ElementAt(index)); } 

ViewBag.TotalItems . Your opinion should know how many items you have on the list. I recommend passing this value as an integer through the ViewBag :

 public ActionResult Index() { ViewBag.TotalItems = myList.Count(); return View(); } 

AJAX and setTimeout . After that, you have it all, you are ready to update your view without updating:

 <script> $(function() { var totalItems = @Html.Raw(Json.Encode(ViewBag.TotalItems)); var currentItemIndex = 0; var getData = function() { $.post("@Url.Action("GetItem")", {index:currentItemIndex}, function(data) { // data is myList.ElementAt(index) // do something with it }).always(function() { currentItemIndex++; if(currentItemIndex < totalItems) { setTimeout(getData, 1000); // get the next item every 1 sec } }) } getData(); // start updating }) </script> 
+5
source

It is best to use @DavidTansey to use SignlarR . It wraps web sockets and returns to a lengthy poll of / etc if the user's browser does not support it. Your users will subscribe to certain channels, and then you can create events in these channels.

As for your business logic, you will need to learn asynchronous programming techniques. As soon as you start with this, you are likely to have more specific questions.

+3
source

All Articles