简体   繁体   English

以MVC ajax形式嵌套的对象可捕获控制器

[英]Nested objects in MVC ajax form to catch in controller

In MVC3 Razor: 在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 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 FormController.cs

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

index.cshtml: 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? 关于为何未将数据填充到FormViewModel对象中的任何想法?

In your FormViewModel, name and address should be properties. 在您的FormViewModel中,名称和地址应该是属性。 The default model binder only works on properties . 默认模型联编程序仅适用于属性

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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