3

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?

1

1 Answer 1

4

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;

enter image description here

Test with Postman

enter image description here

Debug in controller

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

This is what I needed, it told me I was sending too many form values in. That is why it worked with 1 id commented out but not both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.