MVC3 - Ajax loading icon

mp3duck picture mp3duck · Jun 24, 2011 · Viewed 19.6k times · Source

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.

Answer

Chris picture Chris · Jun 24, 2011

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" />
}