Wednesday, January 15, 2014

MVC Ajax Loading Icon when navigating to a new page/action method

Answered by Chad LaCroix on Stackoverflow
Reference:

I kept the link on my menu.cshtml page as an @Html.ActionLink rather than an ajax link. But I added an onclick html attribute that called the javacript to show the spinner.
menu.cshtml
@{
    ViewBag.Title = "Menu";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="container" style="text-align:center">
    <div>
        @Html.ActionLink("Orders", "Index", "Orders", null, new { id = "OrderLink", onclick="showPageLoadingSpinner()" })
    </div>
</div>
I have the scipt for the spinner in my _Layout.cshtml partial view. which is referenced in my menu.cshtml view: Layout = "~/Views/Shared/_Layout.cshtml";
Below is my full _Layout.cshtml page including the ajax div and script references.
_Layout.cshtml
<html>
<head>
    @Content.Script("jquery-1.5.1.min.js", Url)
    @Content.Script("jquery.unobtrusive-ajax.min.js", Url)
</head>

<body>
    <div id="ajaxLoaderDiv" style="position:fixed; top:40%; left:45%; z-index:1234; display:none;">
    </div>
    <div class="container">
         @RenderBody()
    </div>
</body>
</html>

<script type="text/javascript">
function showPageLoadingSpinner() {
     $('#ajaxLoaderDiv').show();
     $('#ajaxLoaderDiv').append(
                '<img src="@Url.Content("~/Images/AjaxLoaderImg.gif")" alt="Loading..."class="ajax-loader" />'
     );
 }

 function hidePageLoadingSpinner() {
     setTimeout(function () {
         $('.ajax-loader').remove();
         $('#ajaxLoaderDiv').hide();
     }, 20000);
 }

</script>

No comments:

Post a Comment