模型绑定绑定在多个级别

时间:2011-03-03 20:02:32

标签: asp.net asp.net-mvc

我有几种形式,所有形式都需要每个省/州的复选框。因此,我已经部分地查看了表单内的复选框以促进代码重用。但是当用户将表单提交给控制器方法时,RegionsViewModel不会被绑定。总体问题是,如何获得多个表单来共享局部视图和查看模型?

以下是我的情况的示例代码 模型

public class Form1ViewModel
{
    /* Some properties */
    public RegionsViewModel Regions {set; get;}
}

public class Form2ViewModel
{
    /* Some properties */
    public RegionsViewModel Regions {set; get;}
}

public class Form3ViewModel
{
    /* Some properties */
    public RegionsViewModel Regions {set; get;}
}

public class RegionsViewModel
{
    public bool ON {set; get;}
    public bool QC {set; get;}
    /* this continues for all provinces and states */
}

控制器

[HttpPost]
public ActionResult Form(Form1VewModel model) {

    //All properties except for model.RegionViewModel does not bind properly to the submitted form :(
}

Form1ViewModel.aspx

<% using (Html.BeginForm())
    {%>
    <!-- Binds some property -->
    <% Html.RenderPartial("Controls/RegionSelector", Model.Regions); %>
    <input type="submit" value="Submit Form!" />
<%}%>

控制/ RegionSelector.ascx

<%=Html.CheckBoxFor(x => x.AvailableProvince_ON> ON
<%=Html.CheckBoxFor(x => x.AvailableProvince_QC> QC
<!-- Binds to all provinces and states -->

更新 用“Model.Region”替换“Model.RegionSelectorVm”。感谢您在我的演示代码Darin Dimitrov中找到错误。

1 个答案:

答案 0 :(得分:1)

什么是RegionSelectorVm?看来这是你偏爱的类型。尝试使用编辑器模板。它更干净:

<% using (Html.BeginForm()) { %>
    <!-- Binds some property -->
    <%= Html.EditorFor(x => x.Regions) %>
    <input type="submit" value="Submit Form!" />
<% } %>

~/Views/Shared/EditorTemplates/RegionsViewModel.ascx内部:

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.RegionsViewModel>" %>
<%= Html.CheckBoxFor(x => x.ON) %> ON
<%= Html.CheckBoxFor(x => x.QC) %> QC

<!-- 
     Continue with inputs for the provinces and states 
     which are part of the RegionsViewModel model 
-->

现在一切都应该正确绑定。