Question

First of all, I am using .Net framework 4, therefore, I can't use Async/Await yet (Yea, I know, I should upgrade to vs 2013).

Anyway, please take a look at the following simple code:

    public ActionResult Index()
    {
        HomeViewModel model = new HomeViewModel();
        var worker = new BackgroundWorker();
        worker.DoWork += (s, e) =>
            {
                model.ItemsToDisplay = SlowProcessList();
            };

        return View(model);
    }

    public static List<string> SlowProcessList()
    {
        List<string> strList = new List<string>();

        strList.Add("First Item");
        Thread.Sleep(3000);

        strList.Add("Second Item");
        Thread.Sleep(3000);

        strList.Add("Third Item");
        Thread.Sleep(3000);

        return strList;
    }

View:

@foreach (var item in Model.ItemsToDisplay)
{
    <p>@item</p>
}

As you can see, I want to return the view first, and then load the data on the background and display it on the form when available. Can anyone guide me to the right direction of doing so?

I'm thinking the proper way to approach this is by: Making a Ajax call on PageLoad and wait for that response.

Was it helpful?

Solution

In HTTP, you only get to send a response once.

HTTP example

You can't send most of the response and then have the server keep working in the background to send more data later.

But that's ok, because your next idea is correct. The way to get around this problem is to use javascript to have the client send more requests and therefore get more data.

Personally, I use AngularJS. Let's take a look at how it works.

  1. The user requests a page (an action).
  2. The webserver delivers the response as a single HTML page.
  3. An Angular controller loads additional data once the page has loaded.
  4. Angular renders the data to the page.

Angular and MVC

You'll need to do some reading up on how AJAX works and what the best way to go about this is. My approach is a little more involved than a jQuery hack, but it's much more maintainable and organised (not a big jQuery fan).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top