当在模型中嵌套的对象中定义属性时,CheckBoxFor 不受限制?
这是一个例子。我有一个 SearchOptions
包含 List<Star>
的模型属性(property)。每个Star
有一个数字、一个名字和一个 bool
应该有界的属性:
public class SearchOptions
{
public SearchOptions()
{
// Default values
Stars = new List<Star>()
{
new Star() {Number=1, Name=Resources.Home.Index.Star1,
IsSelected=false},
new Star() {Number=2, Name=Resources.Home.Index.Star2,
IsSelected=false},
new Star() {Number=3, Name=Resources.Home.Index.Star3,
IsSelected=true},
new Star() {Number=4, Name=Resources.Home.Index.Star4,
IsSelected=true},
new Star() {Number=5, Name=Resources.Home.Index.Star5,
IsSelected=true},
};
}
public List<Star> Stars { get; set; }
}
在我的强类型 View (
SearchOptions
)中,我循环遍历 Stars
属性(property):@using (Html.BeginForm("Do", "Home"))
{
<fieldset>
<legend>@MVC3TestApplication.Resources.Home.Index.Search</legend>
@{
foreach (Star s in Model.Stars)
{
@Html.CheckBoxFor(m => s.IsSelected)
<label>@s.Name</label>
}}
</fieldset>
<input type=submit value="Invia" />
}
Controller 的(相关部分)是:
public ActionResult SearchOptions()
{
return View(new SearchOptions());
}
[HttpPost]
public ActionResult Do(SearchOptions s)
{
// Do some stuff
return View("SearchOptions", s);
}
最佳答案
这是因为您如何访问 CheckBoxFor
中的属性。表达。
@for (int i = 0; i < Model.Stars.Count(); i++) {
@Html.CheckBoxFor(m => m.Stars[i].IsSelected)
<label>@Model.Stars[i].Name</label>
}
这应该适合你。
以下是不同方法的输出:
//using the for loop
<input id="Stars_2__IsSelected" name="Stars[2].IsSelected" type="checkbox" value="true" />
//using the foreach
<input checked="checked" id="s_IsSelected" name="s.IsSelected" type="checkbox" value="true" />
您会注意到 foreach 不包含在进行模型绑定(bind)时与之匹配的正确名称。
关于asp.net-mvc - CheckboxFor 不绑定(bind)嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6781730/