2011-08-29 109 views
1

赶在MVC3剃刀:嵌套对象控制器

我试图创建一个表单,动态,使用领域从多个对象。但出于某种原因,我在控制器中获得的数据不包含输入值。

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目的?

回答

5

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

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

我做了这个改变,它的工作,但现在我有另一个问题。我创建了自定义帮助程序,以便构建表单输入控件并保留我的数据注释并创建数据驱动的表单视图。这解决了如果我使用TextBoxFor的控件的问题,但不是如果我使用我自己的助手(http://stackoverflow.com/questions/7208911/dynamically-call-textboxfor-with-reflection)。任何想法为什么在这里使用反射会失去我的数据?如果我没有嵌套数据并直接捕获其中一个对象,它仍然可以工作。 IE:公共ActionResult保存(名称toSave)与我的帮手获取名称信息。 – KenEucker

+0

我现在意识到为什么它不起作用,那是因为我的反射不在我传递它的对象之上。我想要完成的事情可能是不可能的...... – KenEucker