Paritosh
Paritosh

Reputation: 4503

Get value from CheckBoxFor which are checked

I have a model:

public class SectionModel
{
    public int SectionId { get; set; }
    public string Name { get; set; }
    // used for checkbox
    public bool IsChecked { get; set; }
}

A List of them is returned and setup on a view as checkboxes using:

<div id="TestSections">
  @for (int i = 0; i < Model.Count; i++)
  {
      <div class="form-group">
        <label class="col-md-2 control-label">
            @Model[i].Name
        </label>
        <div class="md-checkbox-list col-md-10">
           <div>
                @Html.CheckBoxFor(m => m[i].IsChecked, new { @SectionId = Model[i].SectionId })
           </div>
        </div>
       </div>
   }
   </div>

This then submits to a action method:

public ActionResult ExamSection(List<SectionModel> model)
{
    var checkedSections = model.FindAll(x => x.IsChecked);
}

the checkedSections returns to me the correct number which were checked, but I need additional details, like the SectionId of which were checked. Is there a way to retrieve it? When I checked the passed in model it only has the IsChecked flag set, all other fields are null.

Upvotes: 1

Views: 606

Answers (3)

jamiedanq
jamiedanq

Reputation: 967

What you should do is add a HiddenField to the Checkbox like below:

       <div>
            @Html.CheckBoxFor(m => m[i].IsChecked)
            @Html.HiddenFor(m =>m[i].SectionId)
       </div>

Then when it posts to the Controller you will have both the IsChecked value and the SectionId value

Upvotes: 4

steve v
steve v

Reputation: 3540

Add a HiddenFor() with the SectionID (and/or name). When it posts, the model will have a value for that field:

  @for (int i = 0; i < Model.Count; i++)
  {
     <div class="form-group">
        <div class="row">
           <label class="col-md-2 control-label">
              @Model[i].Name
           </label>
           <div class="md-checkbox-list col-md-10">
              <div>
                 @Html.HiddenFor(m => m[i].SectionId)
                 @Html.CheckBoxFor(m => m[i].IsChecked)
              </div>
           </div>
        </div>
     </div>
  }

Upvotes: 3

Clint B
Clint B

Reputation: 4700

A form only posts the values of elements that are editable by the user. The only exception I know to that is a hidden field. Which is an input so maybe that's not an exception.

I would add hidden fields to store the values that you are missing.

Upvotes: 1

Related Questions