【问题标题】:Nested objects in MVC ajax form to catch in controllerMVC ajax 形式的嵌套对象在控制器中捕获
【发布时间】:2011-08-30 04:07:05
【问题描述】:

在 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 对象中的任何想法?

【问题讨论】:

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


    【解决方案1】:

    在您的 FormViewModel 中,名称和地址应该是属性。 The default model binder only works on properties.

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

    【讨论】:

    • 我进行了更改并且它有效,但是现在我遇到了另一个问题。我创建了自定义助手以构建表单输入控件并保留我的数据注释并制作数据驱动的表单视图。如果我使用 TextBoxFor,这解决了控件的问题,但如果我使用自己的助手 (stackoverflow.com/questions/7208911/…),则不会。知道为什么在这里使用反射会丢失我的数据吗?如果我没有嵌套数据并直接捕获其中一个对象,它仍然可以工作。 IE: public ActionResult Save(Name toSave) 用我的助手获取Name信息。
    • 我现在意识到为什么它不起作用,那是因为我的反射没有超出我传递它的对象。我想要完成的事情可能是不可能的......
    猜你喜欢
    • 2012-05-30
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 2012-08-31
    相关资源
    最近更新 更多