If you are wondering how to make multiple checkboxes and Multiple checkbox selection (select All or Deselect All),paging, sorting in a MVC3 Webgrid, here is the solution:
To Simplify, It has the following features:
View:
@using NameSpace.DataAccess
@using ThisController = NameSpace.Web.Controllers.HomeController
@model GenericModelTypes<ContactModel>
@{var grid = new WebGrid(rowsPerPage: ThisController._pageSize,
canPage: true, canSort: true, ajaxUpdateContainerId: "webgrid");
grid.Bind(Model.TypeList, rowCount:Model.TotalRecordCount,autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
@grid.GetHtml(
tableStyle: "webgrid",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
htmlAttributes: new { id = "webgrid" },
columns: grid.Columns(
grid.Column(header: "Assign?", style: "labelcolumn",
format:
@<text><input class="check-box" id="assignChkBx" name="assignChkBx" type="checkbox" value="@item.ContactId" /></text>),
grid.Column("CompanyName", "Company Name"),
grid.Column("Title", "Title"),
grid.Column("FirstName", "First Name"),
grid.Column("LastName", "Last Name"),
grid.Column("Street", "Street"),
grid.Column("City", "City"),
grid.Column("State", "State"),
grid.Column("ZipCode", "ZipCode"),
grid.Column("ZipPlus4", "ZipPlus4"),
grid.Column("Phone", "Phone", canSort: false),
grid.Column("Fax", "Fax", canSort: false),
grid.Column("UserName", "AssignedTo")
))
}
I'm returning the model that has two properties (a class [ContactModel] and int property[TotalRecordCount] which has total number of records)
It's important that you tell tell the webgrid, how many total rows it will have; so that its used for paging.
Jquery:
$(document).ready(function () {
$("#toggleAllCheckBox").click(function () {
if ($(this).attr("checked")) {
$(".check-box").attr("checked", true);
} else {
$(".check-box").attr("checked", false);
}
});
});
just add the below anywhere in the body and position accordingly, where you want to display:
<div style="margin-left:75px;" ><input id="toggleAllCheckBox" type="checkbox"/></div>
Domain Model:(this is what typed binded to the View)
public class GenericModelTypes<T> //Generics
{
public IList<T> TypeList { get; set; }
public Int32 TotalRecordCount {get; set;}
}
Supporting Methods in the DAL project:
public GenericModelTypes<ContactModel> GetContacts(String searchValue, int page, int pageSize, String sort)
{
LeadsModelCollection leadscol = new LeadsModelCollection();
IList<ContactModel> addContacts = new List<ContactModel>();
GenericModelTypes<ContactModel> contactModelContainer = new GenericModelTypes<ContactModel>();
try
{
using (SqlConnection sqlcon = new SqlConnection(_connectionString))
{
SqlCommand com = new SqlCommand("sp_GetContacts", sqlcon);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("@search", SqlDbType.NVarChar).Value = searchValue;
sqlcon.Open();
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
ContactModel contact = new ContactModel();
contact.ContactId = (int)dr["ContactId"];
contact.CompanyName = dr["CompanyName"].ToString();
contact.FirstName = dr["FirstName"].ToString();
contact.LastName = dr["LastName"].ToString();
contact.Gender = dr["Gender"].ToString();
contact.Title = dr["Title"].ToString();
contact.Street = dr["Street"].ToString();
contact.City = dr["City"].ToString();
contact.State = dr["State"].ToString();
contact.ZipCode = dr["ZipCode"].ToString();
contact.ZipPlus4 = dr["ZipPlus4"].ToString();
contact.Phone = dr["Phone"].ToString();
contact.Fax = dr["Fax"].ToString();
contact.UserName = dr["UserName"].ToString();
addContacts.Add(contact);
}
}
}
catch (Exception ex)
{
throw new Exception(String.Format("Unable to Fetch:{0}\n{1}\n{2}\n{3}",ex.Message,ex.Source,ex.InnerException,ex.StackTrace));
}
contactModelContainer.TypeList = addContacts;
var Results = contactModelContainer.TypeList.AsQueryable();
contactModelContainer.TotalRecordCount = Results.Count();
Results = Results.Skip(page * pageSize).Take(pageSize);
Results = SortContactResults(sort, Results);
contactModelContainer.TypeList = Results.ToList();
return contactModelContainer;
}
private static IQueryable<ContactModel> SortContactResults(String sort, IQueryable<ContactModel> Results)
{
switch (sort)
{
case "CompanyName":
Results = Results.OrderBy(c => c.CompanyName);
break;
case "FirstName":
Results = Results.OrderBy(c => c.FirstName);
break;
case "LastName":
Results = Results.OrderBy(c => c.LastName);
break;
case "City":
Results = Results.OrderBy(c => c.City);
break;
case "State":
Results = Results.OrderBy(c => c.State);
break;
case "ZipCode":
Results = Results.OrderBy(c => c.ZipCode);
break;
case "ZipPlus4":
Results = Results.OrderBy(c => c.ZipPlus4);
break;
case "UserName":
Results = Results.OrderBy(c => c.UserName);
break;
default:
Results = Results.OrderBy(c => c.CompanyName);
break;
}
return Results;
}
I'm using FULL TEXT Engine to search the table, so used the SQL Connection manually, you can also drag and drop the store procedure in the dbml file(designer view) and use pure LINQ.
The above code first uses SQL connection to fetch data and put it into SQLDBReader, then i used LINQ to SORT and PAGE. There are many ways to do, this is one of the way.
Controller:
public ActionResult LeadsSearch(String searchValue, FormCollection form, int? Page, String sort)
{
var startPage = 0;
Page = Session["Page"] != null ? ((int?)Session["Page"]).Value : 1;
if (Page.HasValue && Page.Value > 0)
{ startPage = Page.Value - 1; }
LeadsManager leadsLibrary = new LeadsManager(); //DAL Project Class
GenericModelTypes<ContactModel> contactList = leadsLibrary.GetContacts(searchValue, startPage, _pageSize, sort);
return View(contactList);
}
Some variables are irrelevant,please ignore.
css:
/* Webgrid */
.webgrid { width:975px;
border: 0px;
border-collapse: collapse;
}
.webgrid a { color: #000;
}
.webgrid-header { padding: 6px 5px;
text-align: center;background-color: #e8eef4;
height: 40px;
border-top: 2px solid #D6E8FF;
border-left: 2px solid #D6E8FF;
border-right: 2px solid #D6E8FF;
border-bottom: 2px solid #3966A2;
}
.webgrid-footer { padding: 6px 5px;
text-align: center;
background-color: #e8eef4;
border-top: 2px solid #3966A2;
height: 30px;
border-bottom: 2px solid #D6E8FF;
border-left: 2px solid #D6E8FF;
border-right: 2px solid #D6E8FF;
}
.webgrid-alternating-row { height: 10px;
background-color: #f2f2f2;
border-bottom: 1px solid #d2d2d2;
border-left: 2px solid #D6E8FF;
border-right: 2px solid #D6E8FF;
}
.webgrid-row-style {
height: 10px;
border-bottom: 1px solid #d2d2d2;
border-left: 2px solid #D6E8FF;
border-right: 2px solid #D6E8FF;
}
.webgrid-selected-row { font-weight: bold; }
That's it you are done!