WebGrid is very rich control to display data in a web page using an HTML table elements. WebGrid will renders data into HTML and it support advance functionalities like asynchronous updates, paging, sorting, custom formatting.
In this blog, I have explained you to use WebGrid in our MVC application.
SQL:
Create Table which shows in List
Now insert data in it
Create Procedure with paging logic like this
In this blog, I have explained you to use WebGrid in our MVC application.
SQL:
Create Table which shows in List
CREATE TABLE [dbo].[tblPersonalDetail] ( [ID] [int] IDENTITY(1, 1) NOT NULL ,[Name] [varchar](500) NULL ,[Address] [varchar](500) NULL ,[ContactNo] [varchar](500) NULL ,[PinCode] [numeric](10, 0) NULL ,CONSTRAINT [PK_PersonalDetail] PRIMARY KEY CLUSTERED ([ID] ASC) WITH ( PAD_INDEX = OFF ,STATISTICS_NORECOMPUTE = OFF ,IGNORE_DUP_KEY = OFF ,ALLOW_ROW_LOCKS = ON ,ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY] ) ON [PRIMARY]
Now insert data in it
SET IDENTITY_INSERT [dbo].[tblPersonalDetail] ON INSERT [dbo].[tblPersonalDetail] ([ID],[Name],[Address],[ContactNo],[PinCode]) VALUES (1,N'Chintan',N'Naranpura',N'77829827',CAST(380014 AS NUMERIC(10, 0)))INSERT [dbo].[tblPersonalDetail] (,[Name],[Address],[ContactNo],[PinCode]) VALUES (1,N'shah',N'Naranpuras',N'77829827',CAST(380014 AS NUMERIC(10, 0)))
Create Procedure with paging logic like this
--dbo.[Demo_Paging_Logic] 1,10,'Name ASC','1=1' ALTER PROCEDURE dbo.[Demo_Paging_Logic] @PageNumber INT = 1 ,@PageSize INT = 5 ,@SortExpression NVARCHAR(20) = 'Name DESC' ,@WhereCondition NVARCHAR(MAX) = ' 1=1 ' AS BEGIN SET NOCOUNT ON; DECLARE @FirstRec INT ,@LastRec INT ,@TotalRows INT SET @FirstRec = (@PageNumber - 1) * @PageSize SET @LastRec = (@PageNumber * @PageSize + 1) SET @TotalRows = @FirstRec - @LastRec + 1 DECLARE @SortExpression1 NVARCHAR(MAX) DECLARE @Query NVARCHAR(MAX) DECLARE @Query1 NVARCHAR(MAX) SET @Query = 'SELECT * FROM(SELECT Cast(ROW_NUMBER() OVER (ORDER BY ' + @SortExpression + ') As int) AS ROWNUM, COUNT(*) OVER(PARTITION BY 1) TotalRecord,* FROM tblPersonalDetail WHERE ' + @WhereCondition + ') AS tbl WHERE ROWNUM > ' + CONVERT(NVARCHAR(10), @FirstRec) + ' AND ROWNUM < ' + CONVERT(NVARCHAR(10), @LastRec) + ' ORDER BY ROWNUM ASC' PRINT @Query EXEC sp_Executesql @Query END GO
After creating this, Add one Entity Framework by ADO.NET Entity Data Model with entity name called TestEntities1.
Model
namespace PiyaPiya.Controllers
{
public class FriendsPageViewModel
{
public int NumberOfFriends { get; set; }
public List<Demo_Paging_Logic_Result> LST { get; set; }
public int FriendsPerPage { get; set; }
}
}
{
public class FriendsPageViewModel
{
public int NumberOfFriends { get; set; }
public List<Demo_Paging_Logic_Result> LST { get; set; }
public int FriendsPerPage { get; set; }
}
}
Controller
#region Web Grid
public ActionResult WebGrid(int page = 1, string sort = "Name", string sortDir = "ASC", string search = null, string ContactNo = null, int? minChildren = null, int? maxChildren = null, string PageSize = "10")
{
ViewBag.PageSize = new List<SelectListItem>() { new SelectListItem() { Text = "5", Value = "5" }, new SelectListItem() { Text = "10", Value = "10", Selected = true }, new SelectListItem() { Text = "20", Value = "20" } };
int FRIENDS_PER_PAGE = Convert.ToInt32(PageSize);//Declare By RV for Page Size
List<Demo_Paging_Logic_Result> obj = new List<Demo_Paging_Logic_Result>();
TestEntities1 _db = new TestEntities1();
obj = _db.Demo_Paging_Logic(page, FRIENDS_PER_PAGE, sort + " " + sortDir, "Name like '%" + search + "%' and ContactNo like '%" + ContactNo + "%'").ToList<Demo_Paging_Logic_Result>();
var data = new FriendsPageViewModel()
{
NumberOfFriends = obj.Count > 0 ? Convert.ToInt32(obj[0].TotalRecord) : 0,
FriendsPerPage = FRIENDS_PER_PAGE,
LST = obj
};
return View(data);
}
public ActionResult WebGrid(int page = 1, string sort = "Name", string sortDir = "ASC", string search = null, string ContactNo = null, int? minChildren = null, int? maxChildren = null, string PageSize = "10")
{
ViewBag.PageSize = new List<SelectListItem>() { new SelectListItem() { Text = "5", Value = "5" }, new SelectListItem() { Text = "10", Value = "10", Selected = true }, new SelectListItem() { Text = "20", Value = "20" } };
int FRIENDS_PER_PAGE = Convert.ToInt32(PageSize);//Declare By RV for Page Size
List<Demo_Paging_Logic_Result> obj = new List<Demo_Paging_Logic_Result>();
TestEntities1 _db = new TestEntities1();
obj = _db.Demo_Paging_Logic(page, FRIENDS_PER_PAGE, sort + " " + sortDir, "Name like '%" + search + "%' and ContactNo like '%" + ContactNo + "%'").ToList<Demo_Paging_Logic_Result>();
var data = new FriendsPageViewModel()
{
NumberOfFriends = obj.Count > 0 ? Convert.ToInt32(obj[0].TotalRecord) : 0,
FriendsPerPage = FRIENDS_PER_PAGE,
LST = obj
};
return View(data);
}
}
#endregion
View
@*PM> Install-Package WebGridMvc*@
@model PiyaPiya.Controllers.FriendsPageViewModel
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
function Clear() {
$(".removeLater").val('');
}
</script>
<style type="text/css">
.grid {
margin: 4px;
border-collapse: collapse;
width: 500px;
background-color: #B4CFC3;
}
.header {
background-color: #C1D4E6;
font-weight: bold;
color: #FFF;
}
.webGrid th, .webGrid td {
border: 1px solid #C0C0C0;
padding: 5px;
width: 10%;
text-align: center;
}
.alt {
background-color: #E4E9F5;
color: #000;
}
.gridHead a:hover {
text-decoration: underline;
}
.description {
width: auto;
}
.select {
background-color: #71857C;
}
</style>
@{
Layout = null;
ViewBag.Title = "WebGrid";
}
<h6>Web Grid</h6>
@{
//var grid = new WebGrid(
//Model.LST,
//rowsPerPage: Model.FriendsPerPage,
//defaultSort: "LookupValuesID",
//columnNames: new[] { "LookupValuesID", "LookupValue" }
// );
var grid = new WebGrid(defaultSort: "Name", canPage: true, rowsPerPage: Model.FriendsPerPage, ajaxUpdateContainerId: "grid");
grid.Bind(Model.LST, autoSortAndPage: false, rowCount: Model.NumberOfFriends);
grid.Pager(WebGridPagerModes.All);
}
@using (Html.BeginForm(null, null, FormMethod.Get))
{
<fieldset>
<legend>Search criteria</legend>
@Html.Label("search", "Name:")
@Html.TextBox("search", null, new { @class = "removeLater" })
@Html.Label("ContactNo", "ContactNo:")
@Html.TextBox("ContactNo", null, new { @class = "removeLater" })
@Html.Label("Page Size", "Page Size:")
@Html.DropDownList("PageSize", (List<SelectListItem>)ViewBag.PageSize)
@*@Html.Label("minChildren", "Children min:")
@Html.TextBox("minChildren", null, new { @class = "num" })
@Html.Label("maxChildren", "Children max:")
@Html.TextBox("maxChildren", null, new { @class = "num" })*@
<input type="submit" value="Apply" />
<input type="submit" value="Clear" onclick="Clear();" />
</fieldset>
}
@grid.GetHtml(
tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
htmlAttributes: new { id = "grid" },
fillEmptyRows: false,
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: grid.Columns
(
grid.Column("ID", header: "ID"),
grid.Column("Name", header: "Name"),
grid.Column("Address", header: "Address"),
grid.Column("ContactNo", header: "ContactNo")
)
)
@model PiyaPiya.Controllers.FriendsPageViewModel
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
function Clear() {
$(".removeLater").val('');
}
</script>
<style type="text/css">
.grid {
margin: 4px;
border-collapse: collapse;
width: 500px;
background-color: #B4CFC3;
}
.header {
background-color: #C1D4E6;
font-weight: bold;
color: #FFF;
}
.webGrid th, .webGrid td {
border: 1px solid #C0C0C0;
padding: 5px;
width: 10%;
text-align: center;
}
.alt {
background-color: #E4E9F5;
color: #000;
}
.gridHead a:hover {
text-decoration: underline;
}
.description {
width: auto;
}
.select {
background-color: #71857C;
}
</style>
@{
Layout = null;
ViewBag.Title = "WebGrid";
}
<h6>Web Grid</h6>
@{
//var grid = new WebGrid(
//Model.LST,
//rowsPerPage: Model.FriendsPerPage,
//defaultSort: "LookupValuesID",
//columnNames: new[] { "LookupValuesID", "LookupValue" }
// );
var grid = new WebGrid(defaultSort: "Name", canPage: true, rowsPerPage: Model.FriendsPerPage, ajaxUpdateContainerId: "grid");
grid.Bind(Model.LST, autoSortAndPage: false, rowCount: Model.NumberOfFriends);
grid.Pager(WebGridPagerModes.All);
}
@using (Html.BeginForm(null, null, FormMethod.Get))
{
<fieldset>
<legend>Search criteria</legend>
@Html.Label("search", "Name:")
@Html.TextBox("search", null, new { @class = "removeLater" })
@Html.Label("ContactNo", "ContactNo:")
@Html.TextBox("ContactNo", null, new { @class = "removeLater" })
@Html.Label("Page Size", "Page Size:")
@Html.DropDownList("PageSize", (List<SelectListItem>)ViewBag.PageSize)
@*@Html.Label("minChildren", "Children min:")
@Html.TextBox("minChildren", null, new { @class = "num" })
@Html.Label("maxChildren", "Children max:")
@Html.TextBox("maxChildren", null, new { @class = "num" })*@
<input type="submit" value="Apply" />
<input type="submit" value="Clear" onclick="Clear();" />
</fieldset>
}
@grid.GetHtml(
tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
htmlAttributes: new { id = "grid" },
fillEmptyRows: false,
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: grid.Columns
(
grid.Column("ID", header: "ID"),
grid.Column("Name", header: "Name"),
grid.Column("Address", header: "Address"),
grid.Column("ContactNo", header: "ContactNo")
)
)