-->

MVC3 - Ajax loading icon

2019-03-10 09:37发布

问题:

I would like to show an ajax loading icon during a 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.

Thanks!

回答1:

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


回答2:

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



回答3:

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.