How can I add a checkbox to each row of a MVCcontrib grid. then when the form is posted find out which records were selected? I Am not finding much when searching for this. Tha
Here's how you could proceed:
Model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsInStock { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var products = new[]
{
new Product { Id = 1, Name = "product 1", IsInStock = false },
new Product { Id = 2, Name = "product 2", IsInStock = true },
new Product { Id = 3, Name = "product 3", IsInStock = false },
new Product { Id = 4, Name = "product 4", IsInStock = true },
};
return View(products);
}
[HttpPost]
public ActionResult Index(int[] isInStock)
{
// The isInStock array will contain the ids of selected products
// TODO: Process selected products
return RedirectToAction("Index");
}
}
View:
<% using (Html.BeginForm()) { %>
<%= Html.Grid(Model)
.Columns(column => {
column.For(x => x.Id);
column.For(x => x.Name);
column.For(x => x.IsInStock)
.Partial("~/Views/Home/IsInStock.ascx");
})
%>
<% } %>
Partial:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
And finally here's a helper method you could use to generate this checkbox:
using System.Web.Mvc;
using Microsoft.Web.Mvc;
public static class HtmlExtensions
{
public static MvcHtmlString EditorForIsInStock(this HtmlHelper htmlHelper)
{
var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttribute("type", "checkbox");
tagBuilder.MergeAttribute("name", htmlHelper.NameFor(x => x.IsInStock).ToHtmlString());
if (htmlHelper.ViewData.Model.IsInStock)
{
tagBuilder.MergeAttribute("checked", "checked");
}
return MvcHtmlString.Create(tagBuilder.ToString());
}
}
Which simplifies the partial:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%: Html.EditorForIsInStock() %>