Base solution for your next web application
Open Closed

Cannot bind complex model #1852


User avatar
0
ianmark89 created

I have a form with viewmodel as bellow

<form role="form" novalidate class="form-validation"> @Html.TextBoxFor(m => m.Class1.TestClass11) @Html.TextBoxFor(m => m.Class1.TestClass12) @Html.TextBoxFor(m => m.Class2.TestClass21) @Html.TextBoxFor(m => m.Class2.TestClass22)

&lt;button id=&quot;btnSave&quot;&gt;Save&lt;/button&gt;

</form>

ViewModel public class ClassViewModel { public Class1 Class1 { get; set; }

    public Class2 Class2 { get; set; }
}

Appservice

public async Task TestCreate(CreateInput input) { }

public class CreateInput
{
    public Class1 Class1 { get; set; }

    public Class2 Class2 { get; set; }
}

When I post back to app service, the input is null

input = _$form.serializeFormToObject(); _testService.TestCreate(input)

I know the issue caused by redundant prefix of serialized object { Class1.TestClass1 ="", Class2.TestClass2 ="" } How can I resolve this issue?


2 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    Hi,

    First of all, this is working model of ASP.NET MVC model binding and not directly related to AspNet Zero.

    When you use Html.TextBoxFor, MVC generates such a form (where textbox names may contain '.' for nested objects). As a short answer, you have 2 options;

    Option 1: Create the js object manually like { class1: { testClass1: ... }, ... } and get values from the form via jQuery.

    Option 2: Do not use form.serializeFormToObject, instead directly post/submit your form and let model binding to MVC.

    Have a nice day.

  • User Avatar
    0
    ianmark89 created

    Thanks for you supporting. I did workaround by creating JavaScript object manually.