MVC ajax形式的嵌套对象用于捕获控制器

时间:2011-08-29 18:11:27

标签: c# asp.net-mvc-3 razor

在MVC3 Razor中:

我正在尝试使用多个对象中的字段动态创建表单。但由于某种原因,我在控制器中获得的数据不包含输入值。

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" /> 
    }

关于为什么没有将数据填充到FormViewModel对象中的任何想法?

1 个答案:

答案 0 :(得分:5)

在FormViewModel中,名称和地址应为属性。 The default model binder only works on properties

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