-1
在檢查框並提交表單後,即使在我檢查了相應的框以使其爲true,ShouldSend字段仍是Controller post方法中的默認值(false)。我擡頭一看類似的問題,這兩個最常見的建議是檢查:CheckBoxFor未能綁定到複雜對象(MVC)
- 複雜的對象索引,以便模型綁定可以在列表
- 我爲了使用CheckBoxFor把他們重新走到一起將複選框的結果綁定到我的模型
我目前正在做這兩件事,但它仍然沒有約束力。其他所有內容都可以正常綁定(例如,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.
}