In this article I will explain with an example, how to display loading image when heavy tasks are executed on
Page Load and Page
PostBacks in
ASP.Net using
JavaScript and
jQuery.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
HTML Markup
The
HTML Markup consists of:
DropDownList – For selecting Country.
Button – For Load Customers.
GridView – For displaying data.
The
GridView consists of three
BoundField columns.
Also, there’s a
HTML DIV which will be used to display the loading progress image.
Country:
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Text="All" Value="" />
<asp:ListItem Text="USA" Value="USA" />
<asp:ListItem Text="Brazil" Value="Brazil" />
<asp:ListItem Text="France" Value="France" />
<asp:ListItem Text="Germany" Value="Germany" />
</asp:DropDownList>
<asp:Button ID="btnSubmit" runat="server" Text="Load Customers" OnClick="OnSubmit" />
<hr />
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Customer Id" />
<asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
</asp:GridView>
<div class="loading" align="center">
Loading. Pleasewait.<br />
<br />
<img src="loader.gif" alt="" />
</div>
Modal background CSS
Following CSS need to place in HEAD section of page for modal background.
<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>
JavaScript for displaying the loading progress image on Page Load and PostBack
The following
JavaScript and
jQuery code creates a modal background and displays a loading image when the
HTML form is submitted.
The
ShowProgress JavaScript method creates a dynamic
HTML DIV element and applies the
CSS class to make it Modal background.
Thus, every time controls like Button, LinkButton, etc. does PostBack the modal window along with the loading progress is shown.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('form').on("submit", function () {
ShowProgress();
});
});
function ShowProgress() {
setTimeout(function () {
var modal = $('<div />');
modal.addClass("modal");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
}, 200);
}
</script>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Displaying the loading progress image on Page Load
Inside the
Page Load event, a
jQuery code snippet is registered which calls the
Button Click event when the
Page is loaded in Browser using the
ClientScript.RegisterStartupScript function.
Above technique will reduce the Page Load time and it will do the major Database operation on Button click.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string script = "$(function (){ $('[id*=btnSubmit]').click(); });";
ClientScript.RegisterStartupScript(this.GetType(), "load", script, true);
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim script As String = "$(function (){ $('[id*=btnSubmit]').click(); });"
ClientScript.RegisterStartupScript(Me.GetType, "load", script, True)
End If
End Sub
Fetching the records from database
When the Submit Button is clicked, the form gets submitted and the modal window along with the loading progress is shown.
Inside the Click event handler, the Thread.Sleep function is used to induce delay and the LoadCustomers method is called.
Note: Thread.Sleep function is used to simulate a long running process. Thus, it must be removed when programming in actual project.
Inside the
LoadCustomers method, the
GridView is populated with records from the
Customers table of the
Northwind database.
The records are filtered based on
Country selected inside the
DropDownList.
C#
protected void OnSubmit(object sender, EventArgs e)
{
// Add Fake Delay to simulate long running process.
Thread.Sleep(5000);
this.LoadCustomers();
}
private void LoadCustomers()
{
string sql = "SELECT CustomerId, ContactName, City FROM Customers WHERE Country = @Country OR @Country = ''";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("@Country", ddlCountries.SelectedItem.Value);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
}
VB.Net
Protected Sub OnSubmit(ByVal sender As Object, ByVal e As EventArgs)
' Add Fake Delay to simulate long running process.
Thread.Sleep(5000)
Me.LoadCustomers()
End Sub
Private Sub LoadCustomers()
Dim sql As String = "SELECT CustomerId, ContactName, City FROM Customers WHERE Country = @Country OR @Country = ''"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("@Country", ddlCountries.SelectedItem.Value)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Using
End Sub
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads