mp3duck
mp3duck

Reputation: 2673

MVC3 - Ajax loading icon

I would like to show an AJAX loading icon during an ActionResult request that can take a few seconds to process.

What is the best approach to accomplished this?

I only want to display the icon after the built it validation passes (I am using MVC3, EF Code First, so the validation is automatically put on the page).

There may be further validation/exceptions during the ActionResult, in which case a message is displayed to the user, and I'd then want the loading icon to disappear again.

Upvotes: 6

Views: 20181

Answers (3)

Denys Wessels
Denys Wessels

Reputation: 17049

Just my two cents:

The solution posted by Chris is valid and will work BUT you must add a reference to the two javascript libraries below. Please note that the order matters:

<script src="~/scripts/jquery-1.8.0.js"></script>
<script src="~/scripts/jquery.unobtrusive-ajax.js"></script>

When you create an MVC application pre-loaded with bundling and all these nu-get packages this will probably not be a problem for you but if you were like me and created an empty ASP.NET MVC application you might run into issues.

Upvotes: 1

Tom Chantler
Tom Chantler

Reputation: 14951

Put the image in a div tag like this:

<div id="busydiv" style="display:none;"><img src="busything.gif" /></div>

and then create your link like this:

@Ajax.ActionLink("Link Text", "ActionName", "ControllerName", null, new AjaxOptions { LoadingElementDuration = 1000, LoadingElementId = "busyDiv", HttpMethod = "Post", UpdateTargetId = "targetDiv", OnFailure = "PostFailure", OnSuccess = "PostSuccess", OnComplete = "PostOnComplete" }, null)

or in a form do this:

@using (Ajax.BeginForm("TestAjax", new AjaxOptions { LoadingElementDuration=1000, LoadingElementId="dave", HttpMethod = "Post", UpdateTargetId = "targetDiv", OnFailure = "PostFailure", OnSuccess = "PostSuccess", OnComplete = "PostOnComplete" }))

Obviously omitting those AjaxOptions that you don't need, as per the documentation here: http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.aspx

Upvotes: 3

Chris
Chris

Reputation: 3201

Define your link as an Ajax action link and specify the ID of a spinning GIF somewhere on your page.

<div id="result"></div>
<img id="spinner" src="../content/ajaxspinner.gif" style="display: none;">
@Ajax.ActionLink("Link Text", "ActionName", "ControllerName", null, new AjaxOptions{UpdateTargetId = "result", LoadingElementId = "spinner"}, null)

or if it is a form:

@using(Ajax.BeginForm("Action", "Controller", null, new AjaxOptions{UpdateTargetId = "result", LoadingElementId = "spinner"}, null))
{
   @Html.TextBox("Data")<br/>
   <input type="submit" value="Submit" />
}

Upvotes: 12

Related Questions