Progress Bar in ASP.NET MVC

Introduction

In this article, we will learn how to create a dynamic progress bar using Bootstrap, Jquery, and JavaScript in ASP.NET MVC.

Basically, a Progress Bar is used to show the progress of any task which is being carried out. Progress bars are usually used to display the download and upload status. Moreover, we can say that Progress Bars can be used to depict the status of anything that is in progress. Since we are integrating this is MVC using C#, we are using Bootstrap, JS, and Jquery to implement this in the webpage So let's see how this can be implemented in MVC in the below article.

Steps

Create an application in ASP.NET MVC web application in Visual Studio.

Go to File menu>New>Project.

Select ASP.NET Web Application (.NET Framework) and change the application name: e.g., ProgressWebsite, and then click OK.

Choose MVC>Now, the MVC web application project is created with the default ASP.NET MVC template.

If you have an existing database then.

Create a Database Model of your existing Database using the Entity Framework.

The database used in the below example is Db1.

Create a table: e.g. EMPLOYEE.

The structure of the table should be as shown below.

  • Name (varchar(50))
  • Father’s Name (varchar(50))
  • Gender (varchar(10))
  • Address (varchar(100))
  • Phone (varchar(12))
  • Mobile No (varchar(10))

If you do not have an existing database, then add a new model in your project and create a new class EMPLOYEE with the above structure.

In this example, we are representing the EMPLOYEE data in a tabular form on a web page where we are loading 4000 records to be displayed, which will show the current loading progress using the Progress Bar.

Now, add a new controller to your project.

Eg: ProgressController

Create a Global instance of the Entity in the controller created above.

Db1 db = new Db1();

Creating a non-parameterized Get Action method namely (Emp_Display) in the controller for the view on which records and the progress bar will be displayed.

public ActionResult Emp_Display()
{   
    var rec = db.EMPLOYEE.ToList();   
    return View(rec);   
}

On the View of the ActionMethod (Emp_Display()) we will create a table to display the headers of the column, as shown below.

<table class="table">  
    <tr>  
        <th>  
            @Html.DisplayNameFor(model => model.Name)  
        </th>  
        <th>  
            @Html.DisplayNameFor(model => model.Father’sName)  
        </th>  
        <th>  
            @Html.DisplayNameFor(model => model.Gender)  
        </th>  
        <th>  
            @Html.DisplayNameFor(model => model.Address)  
        </th>  
        <th>  
            @Html.DisplayNameFor(model => model.Phone)  
        </th>  
        <th>  
            @Html.DisplayNameFor(model => model.Mobileno)  
        </th>  
    </tr>  
    <tbody class="tbody" id="tbody"></tbody>  
</table>

Here, we will leave the table body empty as it will display records that will be fetched using JavaScript. Then we will provide it with a unique ID to identify it when rendering our data.

The classes given to the table above are some of the many bootstrap classes.

In the controller class “ProgressController”, we will Create a JSON web method which will be called with the Ajax Jquery to fetch the data and render it in the view.

[System.Web.Services.WebMethod]
public JsonResult GetText()
{
    Db1 db = new Db1();
    var rec = db.EMPLOYEE.ToList();
    var serializer = new JavaScriptSerializer()
    {
        MaxJsonLength = 999999999
    };
    // Perform your serialization
    serializer.Serialize(rec);
    return Json(rec, JsonRequestBehavior.AllowGet);
}

In the above code, we have attached the WebMethod attribute to a Public method which indicates that we want the method exposed as part of the XML Web service. Adding this attribute to a method within an XML Web service created using ASP.NET makes the method callable from remote Web clients. This class cannot be inherited.

Also, we have used a serializer. Serialize as JsonSerializer converts .NET objects into their JSON equivalent and back again by mapping the .NET object property names to the JSON property names and copies the values for you.

We have implemented the above GetText() Json Action Method that returns the data as JsonResult which is called through Jquery on the View.

After creating JSON WebMethod on the controller, we will create a JS function using AJAX to fetch the data from the WebMethod written above.

Below is the code that will call the WebMethod using Ajax.

Note. Write the below code on the View in a script Tag.

$(document).ready(function() {
    var count = 0;
    var html = '';
    $(".progress-bar").attr("aria-valuenow", "0"); // Setting initial value of progress bar as ‘0’
    $.ajax({
        type: "POST",
        url: "../Progress/GetText",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function(result) {
            $.each(result, function(key, item) {
                $('.table').hide();
                html += '<tr>';
                html += '<td>' + item.Name + '</td>';
                html += '<td>' + item.Father’sName + '</td>';
                html += '<td>' + item.Gender + '</td>';
                html += '<td>' + item.Address + '</td>';
                html += '<td>' + item.Phone + '</td>';
                html += '<td>' + item.Mobileno + '</td>';
                html += '</tr>';
                var myVar = setTimeout(updateProgress, 1, ++count, result.length, html);
                html = "";
            });
            $('.table').show();
        },
        error: function(errormessage) {
            $("#h3").text(errormessage.responseText);
            return false;
        }
    });
});

To display the progress bar, we have to write the below code on the same view page where we want our progress bar and script on the same page as well.

<div class="progress">
    <div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="" aria-valuemin="0" aria-valuemax="100" id="lblStatus">
    </div>
</div>

The below JavaScript function is used to update the progress bar to display the loading of data in percentage.

function updateProgress(count, max, html) {  
    $("#h3").text(count + " Records loaded successfully");  
    var lblStatus = document.getElementById("lblStatus");  
    lblStatus.style.width = count1 + "%";  
    $("#lblStatus").text(count1 + '% Complete');  
    $(".tbody").append(html);  
}

Now, below are the complete code pages explained above.

Controller

public class ProgressController : Controller  
{  
    // GET: Progress  
    Db1 db = new Db1();  
    public ActionResult Index()  
    {  
        return View();  
    }  
    public ActionResult Emp_Display()  
    {  
        return View(db.EMPLOYEE.ToList());  
    }  
    [System.Web.Services.WebMethod]  
    public JsonResult GetText()  
    {  
        Db1 db = new Db1();  
        var rec = db.EMPLOYEE.ToList();  
        var serializer = new JavaScriptSerializer()  
        {  
            MaxJsonLength = 999999999  
        };  
        // Perform your serialization  
        serializer.Serialize(rec);  
        return Json(rec, JsonRequestBehavior.AllowGet);  
    }  
}  

View

@model IEnumerable<SignalR.EMPLOYEE>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="progress">
    <div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="" aria-valuemin="0" aria-valuemax="100" id="lblStatus"></div>
</div>
<h3 id="h3"></h3>
<table class="table">
    <tr>
        <th>
           @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
           @Html.DisplayNameFor(model => model.Father’sName)
        </th>
        <th>
           @Html.DisplayNameFor(model => model.Gender)
        </th>
        <th>
           @Html.DisplayNameFor(model => model.Address)
        </th>
        <th>
           @Html.DisplayNameFor(model => model.Phone)
        </th>
        <th>
           @Html.DisplayNameFor(model => model.Mobileno)
        </th>
    </tr>
    <tbody class="tbody" id="tbody"></tbody>
</table>
<script>
$(document).ready(function() {
    var count = 0;
    var html = '';
    $(".progress-bar").attr("aria-valuenow", "0");
    $.ajax({
        type: "POST",
        url: "../Progress/GetText",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function(result) {
            $.each(result, function(key, item) {
                $('.table').hide();
                html += '<tr>';
                html += '<td>' + item.Name + '</td>';
                html += '<td>' + item.Father’sName + '</td>';
                html += '<td>' + item.Gender + '</td>';
                html += '<td>' + item.Address + '</td>';
                html += '<td>' + item.Phone + '</td>';
                html += '<td>' + item.Mobileno + '</td>';
                html += '</tr>';
                var myVar = setTimeout(updateProgress, 10, ++count, result.length, html);
                html = "";
            });
            $('.table').show();
        },
        error: function(errormessage) {
            $("#h3").text(errormessage.responseText);
            return false;
        }
    });
    var count = 1;
    function updateProgress(count, max, html) {
        $("#h3").text(count + " Records loaded successfully");
        if (count <= max) {
            count1 = parseInt(count / (max / 100));
            var lblStatus = document.getElementById("lblStatus");
            lblStatus.style.width = count1 + "%";
            $("#lblStatus").text(count1 + '% Complete');
            $(".tbody").append(html);
        }
    }
});
</script>

In this article, we have used Javascript, which is a light weighted scripting language that helps us make use of HTML and CSS to display the loading of data in a dynamic way using this highly customizable progress bar/loading indicator on top of the webpage.


Similar Articles