title: Multiple Checkbox selection using Webgrid in MVC 3 (select All/Deselect All), Sorting and Paging
body: <p>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:</p>
  
  <p>To Simplify, It has the following features:</p>
  
  <ol>
  <li>Checkbox in the webgrid</li>
  <li>Multiple checkbox selection (select all /deselect all)</li>
  <li>Paging using LINQ</li>
  <li>Sorting using LINQ </li>
  </ol>
  
  <p>View:</p>
  
  <pre><code>@using NameSpace.DataAccess
  @using ThisController = NameSpace.Web.Controllers.HomeController
  @model GenericModelTypes&lt;ContactModel&gt;
  
       @{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:
                                              @&lt;text&gt;&lt;input class="check-box" id="assignChkBx" name="assignChkBx" type="checkbox" value="@item.ContactId" /&gt;&lt;/text&gt;),
                          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")
                          )) 
  
      }
  </code></pre>
  
  <p>I'm returning the model that has two properties (a class [ContactModel] and int property[TotalRecordCount] which has total number of records)</p>
  
  <p>It's important that you tell tell the webgrid, how many total rows it will have; so that its used for paging.</p>
  
  <p>Jquery:</p>
  
  <pre><code> $(document).ready(function () {
          $("#toggleAllCheckBox").click(function () {
              if ($(this).attr("checked")) {
                  $(".check-box").attr("checked", true);
  
              } else {
                  $(".check-box").attr("checked", false);
  
              }
          });
      });
  </code></pre>
  
  <p>just add the below anywhere in the body and position accordingly, where you want to display:</p>
  
  <pre><code>&lt;div style="margin-left:75px;" &gt;&lt;input id="toggleAllCheckBox" type="checkbox"/&gt;&lt;/div&gt;
  </code></pre>
  
  <p>Domain Model:(this is what typed binded to the View)</p>
  
  <pre><code> public class GenericModelTypes&lt;T&gt; //Generics
      {
          public IList&lt;T&gt; TypeList { get; set; }
  
          public Int32 TotalRecordCount {get; set;}
      }
  </code></pre>
  
  <p>Supporting Methods in the DAL project:</p>
  
  <pre><code>public GenericModelTypes&lt;ContactModel&gt; GetContacts(String searchValue, int page, int pageSize, String sort)
          {
              LeadsModelCollection leadscol = new LeadsModelCollection();
              IList&lt;ContactModel&gt; addContacts = new List&lt;ContactModel&gt;();
              GenericModelTypes&lt;ContactModel&gt; contactModelContainer = new GenericModelTypes&lt;ContactModel&gt;();            
  
              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&lt;ContactModel&gt; SortContactResults(String sort, IQueryable&lt;ContactModel&gt; Results)
          {
              switch (sort)
              {
                  case "CompanyName":
                      Results = Results.OrderBy(c =&gt; c.CompanyName);
                      break;
                  case "FirstName":
                      Results = Results.OrderBy(c =&gt; c.FirstName);
                      break;
                  case "LastName":
                      Results = Results.OrderBy(c =&gt; c.LastName);
                      break;
                  case "City":
                      Results = Results.OrderBy(c =&gt; c.City);
                      break;
                  case "State":
                      Results = Results.OrderBy(c =&gt; c.State);
                      break;
                  case "ZipCode":
                      Results = Results.OrderBy(c =&gt; c.ZipCode);
                      break;
                  case "ZipPlus4":
                      Results = Results.OrderBy(c =&gt; c.ZipPlus4);
                      break;
                  case "UserName":
                      Results = Results.OrderBy(c =&gt; c.UserName);
                      break;
  
                  default:
                      Results = Results.OrderBy(c =&gt; c.CompanyName);
                      break;
              }
              return Results;
          }
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Controller:</p>
  
  <pre><code>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 &amp;&amp; Page.Value &gt; 0)
                  { startPage = Page.Value - 1; }
  
                  LeadsManager leadsLibrary = new LeadsManager(); //DAL Project Class                
                  GenericModelTypes&lt;ContactModel&gt; contactList = leadsLibrary.GetContacts(searchValue, startPage, _pageSize, sort);
                  return View(contactList);
  
  }
  </code></pre>
  
  <p>Some variables are irrelevant,please ignore.</p>
  
  <p>css:</p>
  
  <pre><code>/* 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;  }
  </code></pre>
  
  <p>That's it you are done!</p>