In this article I shall demonstrate how to use the jQuery progress bar in ASP.NET using ajax.
Before going through this article I strongly recommend you go through the basics of jQuery. For reference there are many articles in c-sharpcorner.com.
I shall start with a very small ASP.NET design.
Our page consists of a button control. On a button click a method in the page is invoked. Until the method execution is done the progress bar is updated in the design.
Code Sample
Step 1: Page Design
- <body>
- <form id="form1" runat="server">
- <div id="progressbar"></div>
- <div id="result"></div><br />
- <asp:Label runat="server" ID="lbldisp" Text= "Percentage Completed : "/>
- <asp:Label runat="server" ID="lblStatus" />
- <br />
- <asp:Button ID="btnGetData" runat="server" Text="Get Data" />
- </form>
- lt;/body>
Step 2: Import the jQuery and CSS references.
- <link type="text/css" href="CSS/ui.all.css" rel="stylesheet" />
- <script type="text/javascript" src="Scripts/jquery-1.3.2.js"></script>
- <script type="text/javascript" src="Scripts/ui.core.js"></script>
- <script type="text/javascript" src="Scripts/ui.progressbar.js"></script>
Step 3: Progress Bar set up code.
- <script type="text/javascript" language="javascript">
- $(document).ready(function () {
-
- $("#progressbar").progressbar({ value: 0 });
- $("#lbldisp").hide();
-
- $("#btnGetData").click(function () {
- $("#btnGetData").attr("disabled", "disabled")
- $("#lbldisp").show();
-
- var intervalID = setInterval(updateProgress, 250);
- $.ajax({
- type: "POST",
- url: "Default.aspx/GetText",
- data: "{}",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- async: true,
- success: function (msg) {
- $("#progressbar").progressbar("value", 100);
- $("#lblStatus").hide();
- $("#lbldisp").hide();
- $("#result").text(msg.d);
- clearInterval(intervalID);
- }
- });
- return false;
- });
- });
- /This function is the callback function which is executed in every 250 milli seconds. Until the ajax call is success this method is invoked and the progressbar value is changed.
- function updateProgress() {
- var value = $("#progressbar").progressbar("option", "value");
- if (value < 100) {
- $("#progressbar").progressbar("value", value + 1);
- $("#lblStatus").text((value + 1).toString() +"%");
- }
- }
- </script>
On the button click event the setInterval function is invoked with 2 parameters as input.
- UpdateProgress function
- Delay : 250 milliseconds.
The setInterval function calls the updateProgress function every 250 milliseconds.
Using the jQuery ajax functionality the GetText method in the Default.aspx code is called.
- [System.Web.Services.WebMethod]
- public static string GetText()
- {
- for (int i = 0; i < 10; i ++)
- {
-
-
- Thread.Sleep(2600);
- }
- return "Download Complete...";
- }
I have commented the code in such a way that it helps to understand the functionality.
For a better understanding I have shared the source code.
Output