我有一個CreateViewModel
。將複選框綁定到局部視圖列表
public class CreateViewModel
{
public AttributesViewModel AttributesInfo { get; set; }
}
AttributesViewModel
發送到部分視圖。
public class AttributesViewModel
{
public AttributesViewModel()
{
ChosenAttributes = new List<int>();
}
public List<Attributes> Attributes { get; set; }
public List<int> ChosenAttributes { get; set; }
}
屬性列表在局部視圖中輸出。每個人都有一個複選框。
foreach (var attribute in Model.Attributes)
{
<input type="checkbox" name="ChosenAttributes" value="@attribute.ID" /> @Attribute.Name
}
當我發佈CreateViewModel
,AttributesInfo.ChosenAttributes
始終是空的,即使我查了一些箱子。我如何正確命名每個複選框,以便它綁定到ChosenAttributes列表?
我的解決方案
我把斯蒂芬·馬克的建議,做雙向綁定。所以,我創建了一個包含Value,Text和IsChecked的CheckboxInfo類。我爲它創建了一個EditorTemplate:
@model Project.CheckboxInfo
@Html.HiddenFor(model => model.Text)
@Html.HiddenFor(model => model.Value)
@Html.CheckBoxFor(model => model.IsChecked) @Model.Text
One GIANT警告。爲了正確地工作,我必須爲AttributesViewModel類創建一個EditorTemplate。沒有它,當發佈CreateViewModel時,它不能將複選框鏈接到AttributesInfo。
AttributesInfo.ChosenAttributes不起作用。我會嘗試雙向綁定的方式。 – ScubaSteve
如果您遇到問題,很高興添加代碼,但爲什麼您的'CreateViewModel'只包含一個屬性(對於'AttributesViewModel')? - 或者它是否包含您剛剛省略的其他屬性) –
是的,它包含我省略的其他屬性。這會讓我更加難以理解我的問題與不重要的屬性。 – ScubaSteve