View models are models specific to views. So if your view requires selecting records, create a view model which has an IsSelected property and you can use the CheckBoxFor helper to render check boxes for each of the items in your collection.
You can use editor templates to send the list of checkbox selections to server.
So I would create a view model which represents the selection.
public class EmployeeSelection
{
public bool IsSelected { set; get; }
public string Name { set; get; }
public int Id { set; get; }
}
and add a list of this type to our page view model
public class EmployeeViewModel
{
public List<EmployeeSelection> EmployeeSelections { set; get; }
// Other properties needed for the page also goes here.
// ex: Let's add a Location property
public string Location { set;get;}
}
Now in your GET action, populate the EmployeeSelections property and send to the view.
public ActionResult Create()
{
var vm=new EmployeeViewModel();
vm.EmployeeSelections = manager.getEmployeeData()
.Select(a => new EmployeeSelection() {
Id = a.Id,
Name = a.Name})
.ToList();
return View(vm);
}
Next step is creating an editor template. Create a new razor view called EmployeeSelection.cshtml under ~/Views/Shared/EditorTemplates or ~/Views/{YourControllerName}/EditorTemplates. Have this editor template razor strongly typed to the EmployeeSelection view model. Inside this view, you can use the CheckBoxFor helper method to render checkbox for the model passed to this template. We will also keep the Id property value inside a hidden input.
@model EmployeeSelection
<div>
@Model.Name
@Html.CheckBoxFor(a=>a.IsSelected)
@Html.HiddenFor(a=>a.Id)
</div>
Now in your main view, which is strongly typed to EmployeeViewModel, we can use the EditorFor helper method for the EmployeeSelections property of that page's model(EmployeeViewModel object)
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.LabelFor(a=>a.Location)
@Html.TextBoxFor(a=>a.Location)
<label>Select employees</label>
@Html.EditorFor(a=>a.EmployeeSelections)
<button type="submit">Save</button>
}
This will render the names and checkboxes associated to it (along with the hidden input element for Id). When user submits the form, in your HTTP post action method, you can check the EmployeeSelections and filter that to get the subset which has the IsSelected property set to true
[HttpPost]
public ActionResult Index(IndexVm model)
{
var selected = model.EmployeeSelections.Where(a=>a.IsSelected).ToList();
// If you want Id's select that
var ids = selected.Select(g => g.Id);
// to do : return something
}
EmployeeVMcontainingbool IsSelectedplus the other properties ofEmployeethat you want in the view