Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a method that is looping through a list of values, what I would like to do is when I open the page to be able to see the values changing without refreshing the current view. I've tried something like the code bellow.

public static int myValueReader { get; set; }

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

The actual thing is I want it to read this values even if I close the form. I presume I would need to assign a Task in order to do this, but I was wandering if there is any better way of doing it since it's a MVC application?

like image 653
WKara Avatar asked Dec 14 '15 00:12

WKara


2 Answers

Here's another way to do it:

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

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

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

ViewBag.TotalItems: Your view has to know how many Items you have in your list. I recommend you to pass that value as an integer via ViewBag:

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

AJAX and setTimeout: Once that you have all of this, you're ready to update your view without refreshing:

<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>
like image 190
Santiago Hernández Avatar answered Nov 15 '22 00:11

Santiago Hernández


Your best bet as @DavidTansey mentioned is to use SignlarR. It wraps web sockets and falls back to long polling/etc if the users' browser doesn't support it. Your users will subscribe to specific channels and then you can raise events in those channels.

With regard to your business logic, you'll need to look into async programming techniques. Once you start on this, you'll probably have more specific questions.

like image 44
AJ X. Avatar answered Nov 14 '22 23:11

AJ X.