Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 551
mp3duck Avatar asked Jun 24 '11 10:06

mp3duck


2 Answers

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" />
}
like image 65
Chris Avatar answered Oct 11 '22 10:10

Chris


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

like image 45
Tom Chantler Avatar answered Oct 11 '22 12:10

Tom Chantler