Brian Sweeney
Brian Sweeney

Reputation: 6793

MvcContrib.Grid renders extra hidden input in column

In the following truncated cshtml excerpt i'm using a Grid to build a table:

@using (Html.BeginForm("DeleteSelected", "ControllerName", FormMethod.Post))
{
    @Html.Grid(Model).Columns(column => {
        column
            .For(x => x.CreationTime).Format("{0:g}");
        column
            .For(x => x.OtherPropery);
        column
            .For(x => x.YetAnotherProperty);
        column
            .For(x => Html.CheckBox(x.IdThatICanUseToGrabModels, new {@class = "isSelectedCheck"}))
            .Header(@<div><input type="checkbox" id="isSelectedHeader"/></div>);
    });

When I submit my grid via form POST I'd like to be able to determine which rows were selected and act accordingly in my controller logic. The last column.For(...) statement creates a checkbox input and a hidden input.

Apparently this is the expected behavior. Since the two inputs get the same name, how is one expected to loop over the FormCollection object and get out the correct values? Each key (named x.IdThatICanUseToGrabModels) can end up with more than one value.

How do other people get past this?

thanks,

brian

Upvotes: 1

Views: 1277

Answers (2)

Brian Sweeney
Brian Sweeney

Reputation: 6793

So for now I've solved it like this:

column
    .For(x => Html.Raw("<input name="+x.AMPExamNumber.ToString()+" type=\"checkbox\" />"))
    .Header(@<div><input type="checkbox" id="isSelectedHeader"/></div>);

I can then grab the key-value pairs out of the FormCollection object use them to select my objects from the DB.

This seems awful. If anyone has a better solution please post, lest I am forced to flag this as the solution...

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

The CheckBox/CheckBoxFor helpers are intended to be used with boolean properties on your view model. So:

public class MyViewModel
{
    public DateTime CreationTime { get; set; }
    public string OtherProperty { get; set; }
    public string YetAnotherProperty { get; set; }
    public bool IdThatICanUseToGrabModels { get; set; }
}

and then:

@Html.Grid(Model).Columns(column =>
{
    column.For(x => x.CreationTime).Format("{0:g}");
    column.For(x => x.OtherProperty);
    column.For(x => x.YetAnotherProperty);
    column
        .Custom(@<text>@Html.CheckBox("values", item.IdThatICanUseToGrabModels)</text>)
        .Header(@<div><input type="checkbox" id="isSelectedHeader"/></div>);
})

and finally:

[HttpPost]
public ActionResult DeleteSelected(bool[] values)
{
    ...
}

You could also have a hidden id corresponding to the boolean value (you will have a couple consisting of an id and a boolean property which will allow you in the controller action to know which id is selected).

Upvotes: 2

Related Questions