1

我有一个企业的视图模型。该模型包含一个用于地址、联系方式的视图模型以及一个 IEnumerable。

我使用编辑器模板来显示复选框。问题是当我进行编辑操作并发布表单时,类别返回为空。我已经阅读了一些类似的问题,但还没有找到似乎可行的解决方案。

我调查了自定义模型绑定器,但没有运气,目前我认为我没有在编辑器模板中显示正确的信息。我知道复选框需要一个隐藏的输入来配合它们,也许我的问题就在那里?

业务视图模型

public class BusinessViewModel
    {

        public int? Id { get; set; }

        [UIHint("ContactDetailsEditorTemplate")]
        public ContactDetailsViewModel ContactDetailsViewModel { get; set; }

        [UIHint("CheckboxEditorTemplate")]
        public IEnumerable<CheckboxViewModel> Categories { get; set; }

    }

复选框视图模型

public class CheckboxViewModel
{
    public int CategoryId { get; set;}
    public string Description { get; set;}
    public bool Checked { get; set; }
}

复选框编辑器模板

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<ViewModels.BuyWithConfidence.CheckboxViewModel>>" %>
<table class="aligncenter">
  <tr class="tRow left"><%
    var intBreakLine = 0;
    if (Model != null)
    {
      foreach (var category in Model)
  {
    if (intBreakLine >= 2)
    {
      intBreakLine = 0;%>
      </tr>
      <tr class="tRow left"><%
    }%>
      <td>           
        <%= Html.Hidden(string.Format("Categories[{0}].CategoryID", i), category.CategoryId) %>
        <%= Html.CheckBox(string.Format("Categories[{0}].Checked", i), category.Checked) %>
      </td>
      <td><%=category.Description%></td><%
    intBreakLine = intBreakLine + 1;
    i = i + 1;  
  }
    }%>                        
  </tr>
</table>

这是模板生成的片段:

<input id="Categories_Categories_0__CategoryID" name="Categories.Categories[0].CategoryID" type="hidden" value="1" />
        <input id="Categories_Categories_0__Checked" name="Categories.Categories[0].Checked" type="checkbox" value="true" /><input name="Categories.Categories[0].Checked" type="hidden" value="false" />
4

1 回答 1

1

看起来您最终会得到 3 个输入,所有输入都命名为 CategoryId。您是否考虑过使用.index集合绑定技巧。或者,您可以使用array[]符号。

<%= Html.Hidden("Categories.index", category.CategoryID) %>
<%= Html.Hidden(string.Format("Categories[{0}].CategoryID", category.CategoryID), category.CategoryID) %>
<%= Html.CheckBox(string.Format("Categories[{0}].Checked", category.CategoryID), category.Checked) %>

如果订单保持不变,您可以使用for(int i...)。

<%= Html.Hidden(string.Format("Categories[{0}].CategoryID", i), category.CategoryID) %>
<%= Html.CheckBox(string.Format("Categories[{0}].Checked", i), category.Checked) %>

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

于 2010-06-28T14:33:19.557 回答