【发布时间】:2017-05-06 15:19:06
【问题描述】:
您如何正确地将字典及其每个键的值绑定到复选框? 我可以在 HTTPGET 中显示它们,但将所选值再次绑定到 HTTPPOST 似乎不起作用。
视图模型
public class EditViewModel
{
public Foo Foo { get; set; }
public Dictionary<Bar, List<BarVersionEditVM>> Matrix { get; set; }
}
public class BarVersionEditVM
{
public int ID { get; set; }
public string Name { get; set; }
public string Version { get; set; }
public bool IsSupported { get; set; }
}
查看:
<form asp-action="Edit">
<div class="row">
@foreach (var kvp in Model.Matrix.OrderByDescending(x => x.Key.Name))
{
<div class="col-md-2 col-lg-2">
<fieldset>
<legend>@kvp.Key.Name</legend>
@foreach (var version in kvp.Value)
{
<div>
<input type="checkbox" id="@version.ID" value="@version.IsSupported" name="@version.Name" @(version.IsSupported ? "checked=\"checked\"" : "") />
<label>@version.Version:</label>
</div>
}
</fieldset>
</div>
}
</div>
<input type="hidden" asp-for="@Model.Foo.ID" />
<input type="submit" value="Save" class="btn btn-default" />
</form>
在视图中,我也尝试使用 foreach 和 Html 帮助程序进行重写,但没有成功:
@Html.CheckBoxFor(model => model.Matrix[kvpair.Key][i].IsSupported)
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EditViewModel vm) {
// vm is there but Matrix are null.
// and only the ID of Foo property is filled in.
}
有什么建议吗?
【问题讨论】:
-
DefaultModelBinder不会绑定到值是复杂对象或集合的字典,除非其格式为propertyName[indexer].Key="", propertyName[indexer].Value=""- 在您的情况下 -name=Matrix[0].Key=".."、name="name=Matrix[0].Value[0].ID=".."、@987654328 @ 等,(并且没有帮助方法可以为您生成正确的名称属性)。创建一个代表您的视图的视图模型比使用Dictionary要容易得多 -
例如
EditViewModel包含List<BarVM>和BarVM包含List<BarVersionEditVM>然后使用nestedfor` 循环(或自定义EditorTemplates类型) -
但如果您在视图中显示/编辑的只是这些,您的视图模型可以简单得多。
-
好的,让我试试看。
标签: c# asp.net asp.net-core asp.net-core-mvc