简体   繁体   中英

How to debug ASP.NET Core MVC data binding?

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?

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM