Blog from Saravanan Arumugam

Let us talk about Technologies

Working with MVC 3 razor CheckBoxes


Checkbox helper class works so weird in razor. When we use @Html.CheckBox(), it not only creates an <input type=”checkbox”/>, it creates a hidden input element <input type=”hidden”/>. Microsoft claims that the hidden input element is useful for retuning false when the check box is unchecked. Personally I saw something weird.

When we submit the form, it posts the values of check box status as true or false. When there are multiple checkboxes, the state of the checkboxes are returned as comma separated, true, false series. But as I said, the weird part is,

When a check box is not checked, it posts false.

When a check box is checked, it posts true,false.

For example, if we have 3 checkboxes in a form and all have the same name.

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.CheckBox("fileItem") 
            @Html.Hidden("fileId", item.FileID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FileName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Message)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ProcessDate)
        </td>
    </tr>
}

The code above renders one checkbox for each row of the table.

The following code in the controller would collect the posted form data.

[HttpPost]
public ActionResult ErrorList(FormCollection formData)
{}

Assuming the code above renders 3 checkboxes, the table below would be the result.

Checkbox 1 Checkbox 2 Checkbox 3 formData[“fileItem”]
Unchecked Unchecked Unchecked false,false,false
Checked Unchecked Unchecked true,false,false,false
Unchecked Checked Unchecked false,true,false,false
Unchecked Unchecked Checked false,false,true,false
Checked Checked Unchecked true,false,true,false,false
Unchecked Checked Checked false,true,false,true,false
Checked Unchecked Checked true,false,false,true,false
Checked Checked Checked true,false,true,false,true,false,

 

To identify which row has been selected (using the check boxes’ state),

  1. First thing to do is to create an array of identifiers of each row.
  2. Then gather the indices of checkboxes with the checked state.
  3. Use these indices to get the row identifiers and do the action based on that.

The following code does the above steps.

[HttpPost]
public ActionResult Index(FormCollection formData)
{
    var fileIds = formData["fileId"].Split(',');
    var selectedIndices = formData["fileItem"].Replace("true,false", "true")
                .Split(',')
                .Select((item, index) => new { item = item, index = index })
                .Where(row => row.item == "true")
                .Select(row => row.index).ToArray();
 
    foreach (var index in selectedIndices)
    {
        int fileId;
        if (int.TryParse(fileIds[index], out fileId))
            //Action based on the fileId
    }
 
    return RedirectToAction("MyAction");
}

Note that the formData[“fileItem”] has a Replace method. It replaces true,false to true. This is done because of the behavior of @Html.CheckBox() helper method.

Advertisements

3 responses to “Working with MVC 3 razor CheckBoxes

  1. pandey October 27, 2012 at 7:56 am

    It was nice but please explain in brief

  2. b January 16, 2013 at 5:03 pm

    I ran into this false and true, false issue – very strange. Great post, thank you

  3. Ritesh Man Tamrakar June 26, 2013 at 5:55 am

    thanks for this post

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: