开发者

Nested objects in MVC ajax form to catch in controller

开发者 https://www.devze.com 2023-04-01 02:10 出处:网络
In MVC3 Razor: I am trying to create a form, dynamically, using fields from multiple objects. But for s开发者_开发知识库ome reason the data I get in the controller doesn\'t contain the input values.

In MVC3 Razor:

I am trying to create a form, dynamically, using fields from multiple objects. But for s开发者_开发知识库ome 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;}
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号