Saturday, 30 September 2017

ASP.NET MVC WebGrid Paging, Sorting and showing loading or progress image using Entity Framework

In this article, I am going to explain you ASP.NET MVC WebGrid paging, Sorting and display progress bar or loading image while paging or sorting WebGrid. We will be using visual studio 2013, sql server 2008 r2 and entity framework 6.0.

This article is extension to previous one. In the previous article, we used Dapper ORM to load data but in this demo we will use Entity Framework 6.0 to load record from database and to delete record using checkbox and delete button. Below is the link.
WebGrid Demo
Below is step by step tutorial.

Creating table

Below is the scripts to create a tbl_Employee table and add some dummy data.

CREATE TABLE tbl_Employee
(
EmpID INT PRIMARY KEY IDENTITY,
Name VARCHAR(100),
Salary INT,
City VARCHAR(50),
)
GO
INSERT INTO tbl_Employee VALUES('Rahul',10000,'Mumbai')
INSERT INTO tbl_Employee VALUES('Deepak',15200,'Mumbai')
INSERT INTO tbl_Employee VALUES('Savio',15000,'Delhi')
INSERT INTO tbl_Employee VALUES('Yogesh',10500,'Mumbai')
INSERT INTO tbl_Employee VALUES('Sachin',17000,'Chennai')
INSERT INTO tbl_Employee VALUES('Ponting',80000,'Sydney')
INSERT INTO tbl_Employee VALUES('Josh',24463,'Perth')
INSERT INTO tbl_Employee VALUES('Johnson',24562,'Melbourne')
INSERT INTO tbl_Employee VALUES('Gimmy',32456,'Perth')
INSERT INTO tbl_Employee VALUES('Rocy',68355,'Sydney')
INSERT INTO tbl_Employee VALUES('Rock',99999,'New York')
INSERT INTO tbl_Employee VALUES('Savy',15465,'Chicago')
INSERT INTO tbl_Employee VALUES('Todd',24562,'New York')
INSERT INTO tbl_Employee VALUES('Mary',35485,'New York')
INSERT INTO tbl_Employee VALUES('Mike',15245,'Chicago')

Creating ASP.NET MVC Project

Next step is to create asp.net mvc project.
Go to FileNewProject. A new window will be open as shown below.
Now go to Web and select .NET Framework 4.5 and give project name and click on OK .

Creating asp.net mvc 5 application

Now new window will open as shown below.
Now Select Empty Template, check on MVC checkbox and click on OK.

Selecting asp.net mvc 5 empty template

Now, a new project will be created as shown below.

Asp.net mvc 5 folder structure

Installing Entity Framework and Adding EDMX File

Entity framework will already be included in application if you take .net framework version 4.5. You can check entity framework in references folder of application. Next step is to add .edmx file as shown below.

Go to Model folder → AddNew Item. A new window will be open as shown below.
Go to Data Tab and select ADO.NET Entity Data Model and give its name SampleModel.edmx and click on OK.
Adding entity data model
Select Generate from database and Click on next
Generate from database
Click on New Connection.
Create new connection
Select your server, write your credentials, select database and test for connection.
Select database
Write connection string name.
Connection string name
Click select your table tbl_Employee
Select tables and procedures

Now, rebuild your application.

Adding Controller

Next step is to add controller to application. Add a new empty controller class named as HomeController and add two action methods as shown below. Index method is used to return list of employee to the Index view and DeleteRecords is post method used to delete the records.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebGridDemo.Models;
namespace WebGridDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            SampleEntities obj = new SampleEntities();
            IEnumerable<tbl_Employee> employee = obj.tbl_Employee.ToList();
            return View(employee);
        }

        [HttpPost]
        public ActionResult DeleteRecords(string[] EmpIDs)
        {
            if (EmpIDs != null && EmpIDs.Length > 0)
            {
                foreach (var id in EmpIDs)
                {
                    //to delete Single record
                    //method 1
                    using (SampleEntities entity = new SampleEntities())
                    {
                        int idToRemove = Convert.ToInt32(id);

                        var data = entity.tbl_Employee.SingleOrDefault(x => x.EmpID == idToRemove); //returns a single item

                        if (data != null)
                        {
                            entity.tbl_Employee.Remove(data);
                            entity.SaveChanges();
                        }
                    }

                    /*
                    //method 2
                    using (SampleEntities entity = new SampleEntities())
                    {
                        var employer = new tbl_Employee { EmpID = Convert.ToInt32(id) };
                        entity.tbl_Employee.Attach(employer);
                        entity.tbl_Employee.Remove(employer);
                        entity.SaveChanges();
                    }
                   */
                }
            }
            return RedirectToAction("Index");
        }
    }
}

Adding View

Next step is to add view. Right click inside index action method and add a new view named as Index and select empty model and add a View. Now open Index.cshtml view which is created inside Views/Home folder. Replace all code with below code.

 IEnumerable<WebGridDemo.Models.tbl_Employee>
@{
    ViewBag.Title = "WebGrid Paging Sorting";
    var grid = new WebGrid(canSort: true, rowsPerPage: 5, ajaxUpdateContainerId: "gridContent");
    grid.Bind(source: Model);
}
<!--grid css-->
<style type="text/css">
    .header_style {
        background-color: #055897;
        color: #ffffff;
    }

        .header_style a {
            color: #ffffff !important;
        }

    .table-pager > td {
        padding-top: 10px;
    }

        .table-pager > td > a {
            background-color: #f5f5f5;
            border: 1px solid #ccc;
            border-radius: 3px;
            padding: 3px 7px;
        }

            .table-pager > td > a:hover {
                background-color: #f0f0f0;
            }

    .webgrid-alternating-row {
        background-color: #EAF2D3;
        padding: 3px 7px 2px;
    }
</style>
<!--grid css-->

<meta name="viewport" content="width=device-width, initial-scale=1">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"
        type="text/javascript"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>

<br />
<br />
<h3 class="text-info">Show progress bar or loading image in webgrid in asp.net mvc</h3>
<div class="test" id="gridContent" style="overflow: scroll; width: auto;">
    <div style="width: auto">
        @using (Html.BeginForm("DeleteRecords", "Home", FormMethod.Post))
        {
            if (Model.Count() > 0)
            {
                @grid.GetHtml(
                htmlAttributes: new { id = "idUserGrid" },
                tableStyle: "table table-responsive table-bordered",
                headerStyle: "header_style",
                alternatingRowStyle: "webgrid-alternating-row",
                footerStyle: "table-pager",
                firstText: "First",
                lastText: "Last",
                nextText: "Next",
                previousText: "Previous",
                columns: grid.Columns(
                grid.Column(format: @<text><input type="checkbox" name="EmpIDs" value="@item.EmpID" /></text>, header: "Select"),
                grid.Column("EmpID", "Employee ID"),
                grid.Column("Name", " Name"),
                grid.Column("Salary", "Salary"),
                grid.Column("City", "City")
                ),
                mode: WebGridPagerModes.All
                )
                <div class="navbar navbar-default" role="search">
                    <ul class="nav navbar-nav navbar-form">
                        <li>
                            <input type="submit" class="btn btn-danger" id="btnDelete" value="Delete Selected Records" />
                        </li>
                    </ul>
                </div>
            }
            else
            {
                <p class="text-info, text-danger">No Records Found</p>
                <table class="table table-responsive table-bordered">
                    <thead>
                        <tr class="header_style">
                            <th scope="col">
                                Select
                            </th>
                            <th scope="col">
                                Employee ID
                            </th>
                            <th scope="col">
                                Name
                            </th>
                            <th scope="col">
                                Salary
                            </th>
                            <th scope="col">
                                City
                            </th>
                        </tr>
                    </thead>
                </table>
            }
        }
    </div>
</div>

<!----------popup part----------------------->
<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Modal Header</h4>
            </div>
            <div class="modal-body">
                <p id="error"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(document).on("click", "#btnDelete", function () {
        if ($("#idUserGrid input:checked").length < 1) {
            $("#error").html("Please select at least one record to delete");
            $('#myModal').modal("show");
            return false;
        }
        else {
            return true;
        }
    });
    $(document).on("click", "#idUserGrid tbody tr :checkbox", function () {
        $(this).closest("tr").css("background-color", this.checked ? "#ff9999" : "");
    });
</script>
<!----------popup part----------------------->

<!---------------ajax loading part--------------->
<script type="text/javascript">
    $(document).ajaxStart(function () {
        $("#loading").fadeIn();
    }).ajaxStop(function () {
        $("#loading").fadeOut();
    });
</script>
<div id="loading" class="loading">
    <div class="loadingcontent">
        <p class="loadingspinner">
            @*Loading Please Wait...*@
        </p>
    </div>
</div>
<style type="text/css">
    .loading {
        display: none;
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(255,255,255,0.8);
        z-index: 1000; /*-1*/
    }
    .loadingcontent {
        display: table;
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
    }
    .loadingspinner {
        display: table-cell;
        vertical-align: middle;
        width: 100%;
        text-align: center;
        font-size: larger;
        padding-top: 80px;
        color: #e51f26;
        font-size: medium;
        font-weight: bold;
        background: url(./images/load.gif) no-repeat center;
    }
</style>

<!---------------ajax loading part--------------->

Script File

Add below script file if it not already added in application.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
Below is ajax loading part and add loading gif image in images folder.
<!---------------ajax loading part--------------->
<script type="text/javascript">
    $(document).ajaxStart(function () {
        $("#loading").fadeIn();
    }).ajaxStop(function () {
        $("#loading").fadeOut();
    });
</script>
<div id="loading" class="loading">
    <div class="loadingcontent">
        <p class="loadingspinner">
            @*Loading Please Wait...*@
        </p>
    </div>
</div>
<style type="text/css">
    .loading {
        display: none;
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(255,255,255,0.8);
        z-index: 1000; /*-1*/
    }

    .loadingcontent {
        display: table;
        position: fixed;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
    }

    .loadingspinner {
        display: table-cell;
        vertical-align: middle;
        width: 100%;
        text-align: center;
        font-size: larger;
        padding-top: 80px;
        color: #e51f26;
        font-size: medium;
        font-weight: bold;
        background: url(./images/load.gif) no-repeat center;
    }
</style>

<!---------------ajax loading part--------------->
Initialize grid with ajaxUpdateContainerId="gridContent" and webgrid body should be inside div gridContent as shown below.
var grid = new WebGrid(canSort: true, rowsPerPage: 5, ajaxUpdateContainerId: "gridContent")

<div class="test" id="gridContent" style="overflow: scroll; width: auto;">
    <div style="width: auto">
                        gridcontent
     </div>

</div>        

Output

When the view is loaded the webgrid with data will be shown as below.
WebGrid on view load
When you click on pager or click on column name for sorting then loading image will be shown as below.
Webgrid showing loading image
When you click on checkbox then row background color is changed.
Change webgrid row color on checkbox check
When you try to delete record without checking the rows a popup will be shown using modal.
Show model popup in mvc
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON