CheckBoxFor无法绑定到复杂对象(MVC)

时间:2015-08-26 22:10:34

标签: c# asp.net-mvc model-binding

选中复选框并提交表单后,即使我选中了相应的框以使其成立,ShouldSend字段仍是Controller post方法中的默认值(false)。我已经查找了类似的问题,最常见的两个建议是检查:

  1. 复杂对象被编入索引,因此模型绑定器可以将它们放回列表中
  2. 我使用CheckBoxFor将复选框的结果绑定到我的模型
  3. 我目前正在做这两件事,但它仍然没有约束力。其他所有东西都很好绑定(例如,SidebarViewModel中的MessageTypeViewModel列表)。

    知道为什么我的复选框没有绑定?

    的ViewModels

    public class WrapperViewModel
    {
        public WrapperViewModel()
        {
            Sidebar = new SidebarViewModel();
            Content = new ContentViewModel();
        }
    
        public SidebarViewModel Sidebar { get; set; }
        public ContentViewModel Content { get; set; }
    }
    
    public class SidebarViewModel
    {
        public SidebarViewModel()
        {
            MessageTypeViewModels = new List<MessageTypeViewModel>
            {
                new TypeViewModel {Type = "Type 1", Label = "Label 1"},
                new TypeViewModel {Type = "Type 2", Label = "Label 2"},
    
                // etc.
            };
        }
    
        public IEnumerable<MessageTypeViewModel> MessageTypeViewModels { get; set; }
        public int Field2 { get; set; }
        public int? Field3 { get; set; }
    }
    
    public class MessageTypeViewModel
    {
        public string Type { get; set; }
        public string Label { get; set; }
        public bool ShouldSend { get; set; }
    }
    

    视图

    // Index.cshtml
    @model MessageGeneratorViewModel
    
    @using (Ajax.BeginForm("SendMessages", new AjaxOptions
    {
        HttpMethod = "POST",
        UpdateTargetId = "content",
    }))
    {
        <div id="sidebar">
            <h3>Message Types</h3>
            <ul>
                @Html.EditorFor(m => m.MessageTypeViewModels, "MessageTypeEditorTemplate")
            </ul>
    
            <h3>Target</h3>
            <ul>
                <li>
                    @Html.LabelFor(m => m.Field2)
                    @Html.TextBoxFor(m => m.Field2)
                </li>
                <li>
                    @Html.LabelFor(m => m.Field3)
                    @Html.TextBoxFor(m => m.Field3)
                </li>
            </ul>
    
            <button type="submit">Send Message</button>
        </div>
    }
    
    // MessageTypeEditorTemplate.cshtml
    @model List<MessageTypeViewModel>
    
    @for (int i = 0; i < Model.Count; i++)
    {
        <li>
            <label>
                @Html.CheckBoxFor(m => m[i].ShouldSend)
                @Model[i].Label
            </label>
        </li>
    }
    

    控制器

    public ActionResult SendMessages(WrapperViewModel model)
    {
        // model.Sidebar.MessageTypeViewModels[<any-index>].ShouldSend is false, even if I checked the appropriate box.
    }
    

0 个答案:

没有答案