Html.Grid containing checkbox per row

3.9k Views Asked by At

I am using Html.Grid in my asp.net MVC2 application.

The grid contains checkboxes per row.

<%= Html.Grid<MyViewModel>(Model.MyList)
        .Columns( column => {
            column.For(x => Html.CheckBox("Select", false, new { id = x.ID })).DoNotEncode();

I need to loop through the checked records and action them. How can I retrieve the checked id values when I do a postback on a button click.

Thanks :)

3

There are 3 best solutions below

0
On

You can add like this

x.Add().Encoded(false).Sanitized(false).SetWidth(20).RenderValueAs(y => Html.Raw(" 
<input type='checkbox' value='"+y.IsAdmin+"' ) />"));

it will add checkbox on each row.

0
On

I have this working with more or less the same grid code.

The Checkbox column I have defined more or less the same as yours:

column.For(x => Html.SimpleCheckBox("keys", x.Id.ToString())).DoNotEncode();

The grid is wrapped in a form.

The form posts back to the following method.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Process(IList<int> keys) {
// do stuff with the keys
}

If you have "Select" as the checkbox name, then I guess the parameter name would also be Select.

0
On

You might want to look at a custom ModelBinder.

I am using the grid and I have a checkbox column that looks like this:

column.For(x => Html.CheckBox(x.CatalogItemId +  "-rcvd", false)).DoNotEncode().Named("Received");

My action signature in the controller to handle post back is this:

[HttpPost]
public virtual ActionResult Index([ModelBinder(typeof(PendingRecievedItemsBinder))]IEnumerable<ShelfMyndr.Models.Previews.PendingReceivedCatalogItem> rcvdCatalogItems)

You just need a class that implements IModelBinder. In the BindModel method you can do something like this:

foreach (string key in controllerContext.HttpContext.Request.Form.AllKeys.Where(k => controllerContext.HttpContext.Request[k].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Length > 1))
        {
            if (key.EndsWith("-rcvd"))
            {
                ci.IsReceived = true;
            }

Using this, my controller's action can focus on what do do with a list of items, instead of iterating thru the Forms collection itself.