0

I have a list of employees that I need to show in the following format: a table where is mentioned employee's name, if he's an employee and if he's permanent represented as check boxes.

I also want to be able to check all the checkboxes by checking the box at the left of the column Name and to be able to select an employee by checking the checkbox at the right of each row.

Example: if I check the box at the left of Jhon Smith then the Employee and Permanent columns will be checked.

The checking it shouldn't be a problem with jQuery but I have some hard time binding this to view and then send it back to controller once is saved.

enter image description here

Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
David Dury
  • 5,537
  • 12
  • 56
  • 94

1 Answers1

0

(This is for MVC 4 i'm not sure if anything's changed)

This is pretty easy to do if you're using strongly typed views.

The auto generated "List" type on strongly typed views is similar to that layout.

Assuming this view takes a @model List<EmployeeViewModel>. Create a strongly typed partial view with a CheckBoxViewModel class to use for each employee checkbox property, that has an entry for the label and id of the checkbox with a bool for its checked-ness.

You can then use Html.EditorFor with the CheckBoxViewModels on the EmployeeViewModel to display this partial view. The partial view would be something along the lines of...

    @model CheckBoxViewModel

    @Html.CheckBoxFor(cbox => cbox.Checked)
    @Html.LabelFor(cbox => cbox.Checked, Model.Label)
    @Html.HiddenFor(cbox => cbox.Id)
    @Html.HiddenFor(cbox => cbox.Label)

You might want to miss off the LabelFor looking at your example, but as long as the hidden one is there I think that's fine.

A POST version of the view's controller can then be given an input parameter type of List<EmployeeViewModel> employees which will contain the checkbox values inside the employee objects.

For the tickbox on the left, you can just create a straight HTML version with a plain JavaScript or jQuery event to check the ones in the same row when it is checked/unchecked. Something like that is detailed here - check uncheck All checkboxes with another single checkbox use jquery

Community
  • 1
  • 1
Klors
  • 2,665
  • 2
  • 25
  • 42