Reputation: 85845
I am having a weird problem where I have tons of checkboxes that I need to post to the server yet I need some hidden fields by these checkboxes with id's to do the correct mapping on the server side.
I have something like this (free handed so typos may exist)
MyVm
{
public string Id { get; set; }
public string SecondaryId { get; set; }
public bool IsSelected { get; set; }
public string Name { get; set; }
}
I have a collect of these that I sent to my View
in my view I have
@foreach(var vm in vms) {
<div>
@{ var guid = Guid.New() }
@Html.Hidden("Index", guid, new {id = $"Index[{guid}]"})
@Html.Hidden($"[{guid}.Id", vm.Id)
@Html.Hidden($"[{guid}].SecondaryId", vm.SecondaryId)
@(Html.Kendo().CheckBox().Name($"[{guid}].IsSelected")).Label(vm.Name).Checked(vm.IsSelected)
<div>
}
Now in my controller I have
[HttpPost]
public ActionResult Edit(List<MyVm> vms)
{
// do some stuff
}
Now when I do my post (my code is wrapped in a form tag) "vms" is null.
When I comment out
@foreach(var vm in vms) {
<div>
@{ var guid = Guid.New() }
@Html.Hidden("Index", guid, new {id = $"Index[{guid}]"})
@* @Html.Hidden($"[{guid}.Id", vm.Id) *@
@Html.Hidden($"[{guid}].SecondaryId", vm.SecondaryId)
@(Html.Kendo().CheckBox().Name($"[{guid}].IsSelected")).Label(vm.Name).Checked(vm.IsSelected)
<div>
}
My model binds successfully.
If I comment out
@foreach(var vm in vms) {
<div>
@{ var guid = Guid.New() }
@Html.Hidden("Index", guid, new {id = $"Index[{guid}]"})
@Html.Hidden($"[{guid}.Id", vm.Id)
@* @Html.Hidden($"[{guid}].SecondaryId", vm.SecondaryId)*@
@(Html.Kendo().CheckBox().Name($"[{guid}].IsSelected")).Label(vm.Name).Checked(vm.IsSelected)
<div>
}
My model also binds successfully.
So for whatever reason, having both uncommented out leads me to have a null models but have one or the other leads to model binding.
How can I debug something like this?
Upvotes: 2
Views: 2196
Reputation: 4022
You could check ModelState
property in the controller method to check the reason why the modelbinding was failing.
[HttpPost]
public IActionResult Edit([FromBody] List<MyVm> vms)
{
// do some stuff
var model = this.ModelState;
Test with Postman
Debug in controller
Upvotes: 4