Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Get Checked Rows In a Webgrid Using Checkbox MVC3

5.00/5 (2 votes)
9 Feb 2012CPOL 51.7K  
MVC3 webgrid does not return rows collection, here is a tip to get several objects selected
/*Assuming in a webgrid, someone wants to get a collection of objects that have been checked. MVC3 only returns a single object that has been selected and a count of all rows.
To get a few rows from the webgrid that have been checked, here is a tip on how to do it.

1. Wrap the div containing WebGrid inside a form to be submited */

   @using (Html.BeginForm("Assign","Home"))
   {
     <div id="grid">
        @grid.GetHtml(
        tableStyle: "grid",
        headerStyle: "head",
        alternatingRowStyle: "webgrid-alternating-row",
        columns: grid.Columns(grid.Column(header: "Assign?", format:@<text><input class="check-box"  id="assignChkBx"name="assignChkBx" type="checkbox" value="@item.Id"/></text>)))
     </div>

<p><input type ="submit" value ="Assign" /></p>
    }

//2. Assuming it is as above, define a controller to get the checkbox values
//Selected rows from webgrid
     [HttpPost]  
   public ActionResult Assign(FormCollection form)
   {   
    //get collection of selected ids
    var chckedValues = form.GetValues("assignChkBx");

      //You can use each object if u wish from id
     foreach (var id in chckedValues)
     {
     //get object example..  Customer Customer = Customers.find(id);
     //Your Method here like send an item to customer
     }
   return RedirectToAction("index");
   }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)