views:

1568

answers:

1

I have an MVC Controller that runs through a process, sets some View Data, and then returns the results of this data back to the user in a View. The process time is dependent on the amount of data that is being processed. I need a good way to display an animated .gif within the View while the process is running, letting the user know that something is going on.

I've looked at various AJAX methods and partial views but still cannot find a good way to accomplish this. What I really wished I could do was have an ActionFilter that would return a View or Partial View during the OnActionExecuting event that displays this animated .gif, then once the Controller completed processsing and returned the ViewData, the view or partial view with the actual View Data could be displayed.

It also seems like jQuery would be able to provide a nice asynchronous way to call the controller action in the background and then render the View. Any help would be appreciated.

+11  A: 

In your controller:

public JsonResult GetSomething(int id)
{
    return Json(service.GetSomething(id));
}

In the view (javascript, using JQuery):

$('#someLink').click(function()
{
    var action = '<%=Html.ResolveUrl("~/MyController.mvc/GetSomething/")%>' + $('#someId').val() + '?x=' + new Date().getTime();
    $('loading').show()
    $.getJSON(action, null, function(something) 
    {
        do stuff with something
        $('loading').hide()
    });
});

Note that this assumes a route where 'id' comes after action. The 'x' parameter on the action is to defeat aggressive caching in IE.

In the view (markup):

<img id="loading" src="images/ajax-loader.gif" alt=""/> 
<!-- use a css stlye to make display:none -->

Get loader gifs here.

Also note that you do not have to do this with Json. You can fetch other things like HTML or XML from the controller action if you prefer.

Tim Scott