When my Index view display 2 people and none of them are selected the model validation works correctly due to the MinLengthAttribute in .NET 4.5.
Now comes my custom logic in the ui. When only one person is displayed in the Index view I need no checkbox to check it. The customer can directly press the submit button. I try to manually fill the SelectedIds array see the @else clause.
But this code: Model.SelectedIds = new int[]{ item.PersonId};
Does NOT work, the viewmodel.SelectedIds property on server side action is always {int[0]}
How can I still assign the one person id to the SelectedIds array?
VIEW
@model ListTest.Models.PeopleListViewModel
@{
var hasMoreThanOnePerson = @Model.People.Count > 1;
}
@Html.BeginForm("Save", "Home")
{
@Html.ValidationSummary(false)
<table>
@foreach (var item in Model.People)
{
<tr>
@if (hasMoreThanOnePerson)
{
<td>
<input type="checkbox" name="SelectedIds" value="@item.PersonId" />
</td>
}
else
{
Model.SelectedIds = new int[]{ item.PersonId};
}
<td>
<input type="text" value="@item.Name" />
</td>
</tr>
}
</table>
<input type="submit" value="Save" />
}
VIEWMODEL
public class PeopleListViewModel
{
public PeopleListViewModel()
{
SelectedIds = new int[] { };
}
[MinLength(1, ErrorMessage = "Minimum one person must be selected!")]
public int[] SelectedIds { get; set; }
public List<Person> People { get; set; }
}
CONTROLLER
public ActionResult Index()
{
var people = new List<Person> {
new Person { Name = "Horst", PersonId = 10 },
new Person { Name = "Michael", PersonId = 20}
};
return View(new PeopleListViewModel { People = people });
}
[HttpPost]
public ActionResult Save(PeopleListViewModel viewModel)
{
if (ModelState.IsValid)
{
}
viewModel.People = new List<Person> { new Person { Name = "Horst", PersonId = 10 }, new Person { Name = "bernarnd", PersonId = 20 } };
return View("Index", viewModel);
}