所以我有这个课程,可以让我检查是否选择了颜色:
public class Colors
{
public bool mIsSelected { get; set; }
public string mName { get; set; }
}
在将列表发送到视图之前,我使用以下值填充它:
public List<Colors> mListColors = new List<Colors>();
mListColors.Add(new Colors{ mIsSelected = false, mName = "black"});
mListColors.Add(new Colors { mIsSelected = false, mName = "blue" });
mListColors.Add(new Colors { mIsSelected = false, mName = "white" });
mListColors.Add(new Colors { mIsSelected = false, mName = "red" });
mListColors.Add(new Colors { mIsSelected = false, mName = "green" });
在我看来,我这样渲染它们:
@for (int i = 0; i < Model.mListColors.Count; i++)
{
var item = Model.mListColors[i];
switch (item.mName)
{
case "black":
@Html.Image("~\\Images\\Functional\\blackColor.jpeg", item.mName.ToUpper(), null)
@Html.CheckBoxFor(_item => Model.mListColors[i].mIsSelected, item.mIsSelected)
@Html.HiddenFor(_item => _item.mListColors[i].mName)
break;
case "blue":
@Html.Image("~\\Images\\Functional\\blueColor.jpeg", item.mName.ToUpper(), null)
@Html.CheckBoxFor(_item => Model.mListColors[i].mIsSelected, item.mIsSelected)
@Html.HiddenFor(_item => _item.mListColors[i].mName)
break;
case "red":
@Html.Image("~\\Images\\Functional\\redColor.jpeg", item.mName.ToUpper(), null)
@Html.CheckBoxFor(_item => Model.mListColors[i].mIsSelected, item.mIsSelected)
@Html.HiddenFor(_item => _item.mListColors[i].mName)
break;
case "green":
@Html.Image("~\\Images\\Functional\\greenColor.jpeg", item.mName.ToUpper(), null)
@Html.CheckBoxFor(_item => Model.mListColors[i].mIsSelected, item.mIsSelected)
@Html.HiddenFor(_item => _item.mListColors[i].mName)
break;
case "white":
@Html.Image("~\\Images\\Functional\\whiteColor.jpeg", item.mName.ToUpper(), null)
@Html.CheckBoxFor(_item => Model.mListColors[i].mIsSelected, item.mIsSelected)
@Html.HiddenFor(_item => _item.mListColors[i].mName)
break;
}
}
因此,如果选中复选框,我可能有一个复选框并将值设置为true或false,具体取决于是否为。 HtmlImage是一个自定义帮助程序,允许我显示图像。
但是,无论是否选中此框,控制器中的值始终为false,那么我该怎么做才能纠正?
答案 0 :(得分:0)
您的语法有点偏,您将它们全部设置为false。看here:
// Assign the result of a boolean expression to b.
b = (days % 2 == 0);
答案 1 :(得分:0)
建立Jason Evans的建议你也可以重构你的代码,这样你就不会违反DRY
@for(int idx = 0;idx < Model.ListColors.Count;idx++)
{
var item = Model.ListColors[idx]
@Html.Image(string.Format(
"~\\Images\\Functional\\{0}Color.jpeg",
item.Name.ToLower()), item.Name, null)
@Html.CheckBoxFor(model => Model[idx].IsSelected, item.IsSelected)
@Html.HiddenFor(model => Model[idk].Name)
}
<强>更新强>
您可能需要考虑创建一个更准确地反映您数据的模型:
public class Colors
{
public bool IsSelected {get;set;}
public string Name {get;set;}
}
将您的模型公开为:
@model IEnumerable<Colors>
答案 2 :(得分:0)
如果我再次出错,请低估,但不应该用Value
吗?
@Html.CheckBoxFor(_item => color.Value, Model.mListColors["Blue"].Value)