【问题标题】:Checkbox list for complex type in asp.net mvcasp.net mvc中复杂类型的复选框列表
【发布时间】:2012-09-16 23:38:38
【问题描述】:

我有以下课程:

public class ControllerSecurityModel
{
    public string ControlleName { get; set; }
    public string DisplayName { get; set; }
    public List<ActionSecurityModel> actions { get; set; }
}
public class ActionSecurityModel
{
    public string ActionName { get; set; }
    public string DisplayName { get; set; }
    public bool IsChecked { get; set; }
}

还有一个模型:

public class PageRoleModel
{
    public List<ControllerSecurityModel> AllPages { get; set; }

    public List<ControllerSecurityModel> SelectedPage { get; set; }
}

我想为每个“ActionSecurityModel”设置复选框,我写在下面的视图:

<% using (Html.BeginForm())
   {%>
<% foreach (var cont in Model.AllPages)
   {%>
<fieldset>
    <legend>
        <%= cont.DisplayName  %></legend>
    <% foreach (var act in cont.actions)
       {%>
    <%: Html.CheckBoxFor(x => act.IsChecked) %>
    <%: Html.Label(act.DisplayName) %>
    <% } %>
</fieldset>
<% } %>
<input type="submit" value="save"/>
<% } %>

这是我的控制器操作:

    public ActionResult SetRole()
    {
        PageRoleModel model = new PageRoleModel();

        return View(model);
    }

    [HttpPost]
    public ActionResult SetRole(PageRoleModel model)
    {
        return View(model);
    }

但是当我提交表单时,模型为空? 如何提交复选框并保存?

【问题讨论】:

    标签: c# asp.net-mvc checkbox


    【解决方案1】:

    像这样:

    <% using (Html.BeginForm()) { %>
        <% for (var i = 0; i < Model.AllPages.Count; i++) { %>
        <fieldset>
            <legend>
                <%= Model.AllPages[i].DisplayName %>
            </legend>
            <% for (var j = 0; j < Model.AllPages[i].actions.Count; j++ ) { %>
                <%= Html.CheckBoxFor(x => x.AllPages[i].actions[j].IsChecked) %>
                <%= Html.Label(Model.AllPages[i].actions[j].DisplayName) %>
            }
        </fieldset>
        <% } %>
        <input type="submit" value="save"/>
    <% } %>
    

    要了解为什么我的解决方案有效而您的无效,请阅读默认模型绑定器用于集合的预期 wire format。然后通过浏览生成的 HTML 源代码来查看生成的表单输入字段的名称 - 您将很快看到复选框的 name 属性的根本区别。

    也不要期望在 POST 操作中绑定整个模型。您的表单中只有一个输入字段 - 一个复选框。所以这是唯一要发送到服务器并绑定到模型的值。如果您还需要其他值,您可以将它们包含为隐藏字段:

    <!-- in the outer loop: -->
    <% =Html.HiddenFor(x => x.AllPages[i].DisplayName) %>
    ...
    <!-- and then in the inner loop -->
    <%= Html.HiddenFor(x => x.AllPages[i].actions[j].ActionName) %>
    <%= Html.HiddenFor(x => x.AllPages[i].actions[j].DisplayName) %>
    ... and so on ...
    

    此外,我强烈建议您使用编辑器模板,而不是在视图中编写这些循环。他们会自动为您的输入字段生成正确的名称,这样您就不必担心了。关于这个话题,我有无数的答案。只需谷歌我的名字并将editor templates asp.net mvc 添加到您的搜索中,您应该会得到很多结果。

    【讨论】:

      猜你喜欢
      • 2013-08-05
      • 1970-01-01
      • 2011-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      相关资源
      最近更新 更多