In this article I will explain with an example, how to display (show) Loading Progress GIF Image when Page Loads in ASP.Net MVC Razor.
The Loading Progress GIF Image will be displayed in center of Page (View) and will be shown when the Page has started loading in Browser and it will be hidden as soon as the Page loading is completed using JavaScript.
Controller
The Controller consists of the Index Action method. Inside this Action method, simply the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
View
Inside the View, the ShowProgress JavaScript method is called at the start of BODY tag.
The ShowProgress JavaScript method, creates a dynamic HTML DIV element and applies the CSS class to make it Modal background.
Then the Loading DIV is placed in center of the Modal DIV and made visible.
At the end of BODY tag, there’s a window.onload event handler which is executed when the Page (View) is completely loaded in browser.
Inside the window.onload event handler, the dynamic Modal DIV is removed and the Loading DIV is hidden.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
.modal {
position: fixed;
top: 0;
left: 0;
background-color: black;
z-index: 99;
opacity: 0.8;
filter: alpha(opacity=80);
-moz-opacity: 0.8;
min-height: 100%;
width: 100%;
}
.loading {
font-family: Arial;
font-size: 10pt;
border: 5px solid #67CFF5;
width: 200px;
height: 100px;
display: none;
position: fixed;
background-color: White;
z-index: 999;
}
</style>
</head>
<body>
<div class="loading" align="center">
Loading. Please wait.<br/>
<br/>
<img src="/Images/loader.gif" alt=""/>
</div>
<script type="text/javascript">
var modal, loading;
function ShowProgress() {
modal = document.createElement("DIV");
modal.className = "modal";
document.body.appendChild(modal);
loading = document.getElementsByClassName("loading")[0];
loading.style.display = "block";
var top = Math.max(window.innerHeight / 2 - loading.offsetHeight / 2, 0);
var left = Math.max(window.innerWidth / 2 - loading.offsetWidth / 2, 0);
loading.style.top = top + "px";
loading.style.left = left + "px";
};
ShowProgress();
</script>
<!-- Keep the Page Content Here.-->
<script type="text/javascript">
window.onload = function () {
setTimeout(function () {
document.body.removeChild(modal);
loading.style.display = "none";
}, 2000); //Delay just used for example and must be set to 0.
};
</script>
</body>
</html>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Downloads