0

我正在做一个 ASP.NET MVC 项目,我有一个嵌套模型如下:

public class A
.........

public class B
.............

public class AB
{
  public A _a;
  public B _b;
  public AB()
  {
    _a = new A();
    _b = new B();
  }
}

在控制器中:

public ActionResult Create()
{
  AB model = new AB();
  return View(model);
}

[HttpPost]
public ActionResult Create(AB abModel)
{
  //all properties of abModel._a and abModel._b are null 
  return View(abModel);
}

我的视图是 AB 模型类的强类型视图,我不知道为什么所有回发的值都是空的,这只发生在嵌套模型中。我错过了什么吗?

谢谢你帮助我

@rene 提议的更新模型

public class AB
{
  public A _a {get; set};
  public B _b {get; set};
  public AB()
  {
    _a = new A();
    _b = new B();
  }
}

查看代码:

  @model TestMVC.AB    
    @{
        ViewBag.Title = "Create";
    }
    @using (Html.BeginForm()) {
     @Html.ValidationSummary(true)
       <table cellspacing="0" cellpadding="0" class="forms">

       <tbody>
              <tr><th>
            @Html.LabelFor(model => model._a.ClientName)
      </th>
      <td>
            @Html.TextBoxFor(model => model._a.ClientName, new { @class = "inputbox"})
            @Html.ValidationMessageFor(model => model._a.ClientName)
       </td></tr>
      <tr><th></th><td><input type="submit" value="Create" /></td></tr>
      </tbody></table>

    }
4

2 回答 2

2

MVC 模型绑定器仅绑定到属性而不绑定到字段。这个模型适用于我在 MVC3 中的控制器和视图

按如下方式更改模型类:

public class A
{
    public string ClientName { get; set; }
}

public class B
{
    public string Address { get; set; }
}

public class AB
{
    public A  _a { get; set;}
    public B _b { get; set;  }
}
于 2012-09-01T08:50:21.223 回答
1

为了让模型绑定器捕获它们,它们需要在 HTML 表单中命名为子属性。根据您构建视图的方式,它们可能不会自动生成。检查您的表格

<input name="_a.descendant">

如果您的子属性具有模板并且没有自动使用它们,则可能需要:

@{ Html.RenderPartial("Template_A", Model._a, new ViewDataDictionary {
    TemplateInfo = new System.Web.Mvc.TemplateInfo {
         HtmlFieldPrefix = "_a"
    }
});}
于 2012-09-01T08:56:06.103 回答