1

I have a function that gets a lot of data from the internet. It takes about 15 seconds to get all the data. How can I display a text (like "loading data"), while It is still loading. Right now, it looks like this:

  1. I enter the page

  2. My "Index" loads my "LoadData" function.

  3. The function stores the data into ViewBags

  4. The function returns the View

In the View:

<table class='table' id='vmTable' border='1'>
    <tr>
        <th>VM Name</th>
        <th>Status</th>
        <th>Shutdown Time</th> 
        <th>Service Name</th> 
        <th>Created Date</th> 
        <th>Last Modified</th>
        <th>Port</th>
    </tr>

    @for (int i = 0; i < ViewBag.AmountOfVms; i++)
    {
        <tr class="tableColumn vmColumn">
            <td class="vmName">@ViewBag.VMs[i, 0]</td>
            <td class="vmStatus">@ViewBag.VMs[i, 1]</td>
            <td class="vmShutDown">@ViewBag.VMs[i, 6]</td>
            <td class="vmServiceName">@ViewBag.VMs[i, 2]</td>
            <td class="vmCreatedDate">@ViewBag.VMs[i, 3]</td>
            <td class="vmLastModified">@ViewBag.VMs[i, 4]</td>
            <td class="vmPort">@ViewBag.VMs[i, 7]</td>
        </tr>
    }

</table>

Ive heard about Ajax and using Partial Views. So, can I display my table as a partial View and just say

@if (ViewBag.VMs[i, 0] == null)
{
    <td>Loading...</td>
}

And then refresh the Partial View every second? And how can I run my "LoadData" function while being on the page. Or in other words: How can I just display "loading" while the ViewBag is null.

Do you have any good examples for this?¨

tereško
  • 58,060
  • 25
  • 98
  • 150
user2877820
  • 287
  • 4
  • 19

2 Answers2

1

First of all i would recommend you started using a Model instead of the ViewBag.

ViewBag vs Model, in MVC.NET

Secondly you just use a technology called Ajax :)

Render Partial View Using jQuery in ASP.NET MVC

You can see an example here :)

Community
  • 1
  • 1
Softwarehuset
  • 815
  • 4
  • 10
1

Razor code is evaluated at server side. This means that once the client has the view loaded, there is no code to run anymore. The page just sits there. You cannot write a while-loop (in Razor) that loads a partial view if viewbag is empty. You need to do this in JavaScript.

If you want the page to refresh all the time, you will need a timer. Use jQuery .get() to load the partial view via AJAX. When using AJAX to handle the request, you can use jQuery .ajaxStart() and .ajaxComplete() to show and hide a "Loading..." label.

.get()

.ajaxStart()

.ajaxComplete()

Kim
  • 829
  • 7
  • 12