简体   繁体   中英

Nested objects in MVC ajax form to catch in controller

In MVC3 Razor:

I am trying to create a form, dynamically, using fields from multiple objects. But for some reason the data I get in the controller doesn't contain the input values.

FormViewModel.cs

    namespace DynamicForm.Models
    {
        public class FormViewModel
        {
            public Name name = new Name();
            public Address address = new Address();

            public FormViewModel()
            {
            }
        }

public class Name
    {
        [Required()]
        public String first { get; set; }
        [Required()]
        public String last { get; set; }

        public Name()
        {
            first = "";
            last = "";
        }
    }
    public class Address
    {
        public String street1 { get; set; }
        public String street2 { get; set; }

        public Address()
        {
            street1 = "";
            street2 = "";
        }
    }

    }

FormController.cs

[HttpPost()]
        public ActionResult Save(FormViewModel toSave)
        {
            return View();
        }

index.cshtml:

@using DynamicForm;
@using DynamicForm.Models;
@model FormViewModel

@{
    ViewBag.Title = "Form";
}

<h2>Form</h2>

    @using (Html.BeginForm("Save", "Form"))
    { 
        @Html.TextBoxFor(m => m.address.street1)
        @Html.TextBoxFor(m => m.address.street2)

        @Html.TextBoxFor(m => m.name.first)
        @Html.TextBoxFor(m => m.name.last)

        <input type="submit" value="Send" /> 
    }

Any ideas as to why the data isn't being populated into the FormViewModel object?

In your FormViewModel, name and address should be properties. The default model binder only works on properties .

public class FormViewModel
{
    public Name Name {get;set;}
    public Address Address {get;set;}
}

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