When working with objects of the list type, you must refer to them using array notation so that the field names are generated in such a way that the model node can analyze them, i.e.
for (var i = 0; i < Model.Count(); i++) { @Html.LabelFor(m => Model[i].SomeProperty) @Html.EditorFor(m => Model[i].SomeProperty) }
In your scenario, you would be better off using the view model to contain your list and adding the Selected property to the elements so you can keep track of which ones were or were not selected.
public class ViewModelProspects { public List<ViewModelProspectSelect> Prospects { get; set; } } public class ViewModelProspectSelect { // Whatever else you have public bool Selected { get; set; } }
Then, in your opinion:
@model ViewModelProspects @using (Html.BeginForm()) { for (var i = 0; i < Model.Prospects.Count(); i++) { <label> @Html.HiddenFor(m => Model.Prospects[i].Id) @Html.CheckboxFor(m => Model.Prospects[i].Selected, true) @Model.Prospects[i].Name </label> } }
And finally, change the signature of your action:
[HttpPost] public ActionResult UsersInProspect(ViewModelProspects model)
Then you can easily get a list of selected identifiers within the action with:
var selectedIds = model.Prospects.Where(m => m.Selected).Select(m => m.Id)
Chris pratt
source share