我的 ViewModel 中有一个列表,我将其解析为 View
List<BoolSetting>
bool 设置:
public class BoolSetting
{
public BoolSetting(string displayName, bool value)
{
DisplayName = displayName;
Value = value;
}
public string DisplayName { get; set; }
public bool Value { get; set; }
}
然后我想为列表中的所有项目打印一个复选框,因此列表位于 View 使用的 ViewModel 中
@foreach(var boolSettingList in Model.BoolSettingList)
{
<div>
@Html.CheckBox(boolSettingList.DisplayName, boolSettingList.Value)
@boolSettingList.DisplayName
</div>
}
问题是当我发布这个时,我的模型没有在我的 ViewModel 的列表中保存更新的设置( bool 值),因此该对象是空的。
我可以
foreach (var VARIABLE in userSettingConfigViewModel.BoolSettingList)
{
VARIABLE.Value = (bool)Request.Form[VARIABLE.DisplayName];
}
但是这个 View 模型会有很多列表,其中一些会重名!这样就会引起冲突
那么有没有一种方法可以 foreach 打印我所有的 bool 值,然后让 MVC 弄清楚之后将数据放回 List 对象中?我无法让 CheckBoxFor 工作,因为它需要一个表达式,而且我无法想出一种方法来迭代我的列表
我可以通过为 BoolSetting 和 List 制作模板来使用模板修复它吗?
最佳答案
首先修复您的 View 模型并删除自定义构造函数,否则默认模型绑定(bind)器将无法实例化它,您将不得不编写自定义模型绑定(bind)器和其他东西:
public class BoolSetting
{
public string DisplayName { get; set; }
public bool Value { get; set; }
}
public class MyViewModel
{
public List<BoolSetting> Settings { get; set; }
}
然后编写一个将填充您的 View 模型的 Controller 操作:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Settings = new[]
{
new BoolSetting { DisplayName = "name 1", Value = true },
new BoolSetting { DisplayName = "name 2", Value = false },
new BoolSetting { DisplayName = "name 3", Value = true },
}.ToList()
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
然后是一个 View (~/Views/Home/Index.cshtml
),您只需在其中使用编辑器模板而不编写任何 foreach
循环或弱类型 html帮助程序,例如 Html.CheckBox
。通过使用编辑器模板,您将确保所有输入字段都具有正确的名称,以便默认模型绑定(bind)器能够在回发期间将它们的值提取到 View 模型中:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Settings)
<button type="submit">OK</button>
}
最后是 View 模型的相应编辑器模板,它将为集合中的每个元素呈现 (~/Views/Home/EditorTemplates/BoolSetting.cshtml
):
@model BoolSetting
<div>
@Html.CheckBoxFor(x => x.Value)
@Html.LabelFor(x => x.Value, Model.DisplayName)
@Html.HiddenFor(x => x.DisplayName)
</div>
关于c# - 从 List<T> 创建 MVC3 CheckBoxFor 并在 Post 上取回列表(具有更新的值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8356703/