将我的视图模型绑定到视图会导致选中所有复选框
本文关键字:视图 复选框 模型 我的 绑定 | 更新日期: 2023-09-27 17:56:17
我遇到了一个问题,即视图中呈现的所有复选框都处于选中状态。我在构造视图模型的行处放置了一个断点,通过调试器,我可以看到某些值设置为"true",而其他值设置为"false"。所以,我假设,问题必须出在视图本身。
这是我的模型:
public class UserModulesAdministrationViewModel
{
public bool AccessGranted { get; set; }
public int ModuleId { get; set; }
public string ModuleName { get; set; }
public string ModuleDescription { get; set; }
}
这是我正在呈现列表的控制器:
public ActionResult UserModules(int id)
{
// Database stuff here
var model = modules.Select(module => new Infrastructure.ViewModels.UserModulesAdministrationViewModel
{
ModuleId = module.AccessModuleId,
AccessGranted = userModules.Any(z => z.AccessModuleId == module.AccessModuleId),
ModuleName = module.ModuleName,
ModuleDescription = module.ModuleDescription
}).ToList();
return View(model);
}
最后这是我的相关视图代码:
@model IEnumerable<UserModulesAdministrationViewModel>
@foreach (UserModulesAdministrationViewModel m in Model)
{
<div class="col-md-4" style="margin-top: 15px;">
<div class="moduleBlockLong" style="position: relative">
<div class="moduleHeader">@m.ModuleName</div>
<div class="moduleText">@m.ModuleDescription</div>
<div class="checkbox" style="position: absolute; bottom: 0; right: 80px">
<label>
@{
var m1 = m;
}
@Html.CheckBoxFor(z => m1.AccessGranted )
<input type="checkbox" value="" checked="checked"/> Allow Access
</label>
</div>
</div>
</div>
}
在我看来
,问题就像您在CheckBoxFor
HtmlHelper
之后对输入进行了硬编码。
@Html.CheckBoxFor(z => m1.AccessGranted )
<input type="checkbox" value="" checked="checked"/>
删除:
<input type="checkbox" value="" checked="checked"/>
还值得注意的是,由于您使用的是foreach
循环而不是for
循环,因此您将无法将所选值发布回服务器。
您需要按如下方式为循环编制索引:
@for (var i = 0; i < Model.Count; i++)
{
// code
@Html.CheckBoxFor(z => Model[i].AccessGranted)
// rest of code
}
否则,您将无法读取服务器上的任何用户输入。
在您看来,删除
<input type="checkbox" value="" checked="checked"/> Allow Access
由于checked="checked"
,这将始终打印出选中的复选框。
我认为这是因为您离开了<input type="checkbox" value="" checked="checked"/>
删除它,它将起作用。
关于循环还存在另一个问题foreach
。
ASP.NET MVC 4 - 用于循环帖子模型集合属性,但 foreach 不
溶液:
@for(var i = 0; i<Model.Count; i++)
{
<div class="col-md-4" style="margin-top: 15px;">
<div class="moduleBlockLong" style="position: relative">
<div class="moduleHeader">@Model[i].ModuleName</div>
<div class="moduleText">@Model[i].ModuleDescription</div>
<div class="checkbox" style="position: absolute; bottom: 0; right: 80px">
<label>
@Html.CheckBoxFor(z => Model[i].AccessGranted) Allow Access
</label>
</div>
</div>
</div>
}
试试这段代码...而不是 : <input type="checkbox" value="" checked="checked"/> Allow Access
尝试: <input type="checkbox" value="" checked="@m.AccessGranted "/> Allow Access
此外,不要使用 m1 参数。