MVCContrib Grid:
@model ViewModel
@using (Html.BeginForm("SendData", "Home", FormMethod.Post))
{
@Html.Grid(Model.List).Columns(c =>
{
c.For(x => x.Id);
c.For(x => x.Name);
c.For(x =>Html.Partial("Partial/CheckBoxTemplate", new CheckBoxViewModel { Id = x.Id })).Named("Options");
})
@Html.SubmitButton()
}
Controller Post Action:
public ActionResult SendData(List<CheckBoxViewModel> list)
{
return View();
}
ViewModels:
public class CheckBoxViewModel
{
public int Id { get; set; }
public bool CheckBox { get; set; }
}
public class ViewModel
{
public IPagination<Data> List { get; set; }
}
public class Data
{
public int Id { get; set; }
public string Name { get; set; }
}
Partial View:
@model MvcApplication1.Models.CheckBoxViewModel
@Html.HiddenFor(x => x.Id)
@Html.CheckBoxFor(x => x.CheckBox)
All checkboxed are by default not checked.
How can I retrieve all checked checkbox values in my SendData
action?
I would recommend you to use a real view model that will reflect the requirements of your view (displaying a grid containing for each row a checkbox, and displaying the id and name of the item and retrieving those values in a list in your postback action):
public class CheckBoxViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool CheckBox { get; set; }
}
public class ViewModel
{
public IPagination<CheckBoxViewModel> List { get; set; }
}
and then have your view strongly typed to this view model:
@model ViewModel
@using (Html.BeginForm("SendData", "Home", FormMethod.Post))
{
@Html.Grid(Model.List).Columns(c =>
{
c.For(x => x.Id);
c.For(x => x.Name);
c.For(x => Html.Partial("Partial/CheckBoxTemplate", x)).Named("Options");
})
<button type="submit">OK</button>
}
finally your partial could look like this:
@model CheckBoxViewModel
@{
var index = Guid.NewGuid().ToString();
}
@Html.Hidden("list.Index", index)
@Html.Hidden("list[" + index + "].Id", Model.Id)
@Html.Hidden("list[" + index + "].Name", Model.Name)
@Html.CheckBox("list[" + index + "].CheckBox", Model.CheckBox)
Now when the SendData
action is invoked it will be passed the list of your view model.
Alternatively you could use the Html.BeginCollectionItem
helper presented in the following article
which would allow you to use the strongly typed versions of the helpers:
@model CheckBoxViewModel
@using(Html.BeginCollectionItem("list"))
{
@Html.HiddenFor(x => x.Id)
@Html.HiddenFor(x => x.Name)
@Html.CheckBoxFor(x => x.CheckBox)
}
Recommended further reading: Model Binding To A List
.