我正在 View 上创建 x 个下拉列表,并希望将所选值绑定(bind)回发布时的 View 模型。我见过斯科特的post并尝试编写我的代码,但仍然无法使其工作。
我的 View 模型由两项组成。一种用于下拉列表的名称标签,另一种用于选定的值。我需要选定的值,因为我需要预先选择下拉列表。
虚拟机
public class ColumnMapperVm
{
public string Column { get; set; }
public string SelectedValue { get; set; }
}
View 采用 View 模型列表。原因是因为我不知道设计时需要的下拉列表的数量。因用户而异。
@model List<ColumnMapperVm>
@for (int i = 0; i < Model.Count; i++ )
{
<tr>
<td style="width: 50%;">
@Html.DisplayFor(m => m[i].Column)
</td>
<td>
@Html.DropDownList("SelectedValue", new SelectList(ViewBag.Columns, "StaticName", "DisplayName", Model[i].SelectedValue))
</td>
</tr>
}
我将选择列表放在 View 袋中,因为我想保持我的 View 模型清晰,并且我不选择列表将不会被发布回服务器。
这是我的 Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MapColumns(List<ColumnMapperVm> colmapper)
{
//colmapper is null
}
当然,我在 FormCollection 中获取了值,但模型绑定(bind)器没有绑定(bind) View 模型,我想知道如何使其工作。
最佳答案
一个可能的原因可能是当前帖子上的所有下拉列表都向请求添加了同名的值。要解决此问题,您可以使用 DropDownListFor
:
@Html.DropDownListFor(m => m[i].SelectedValue, new SelectList(ViewBag.Columns, "StaticName", "DisplayName"))
这应确保所有下拉菜单在 HTML 标记中具有正确的名称。
关于c# - 如何在 mvc 中绑定(bind)复杂对象列表以查看帖子上的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23111839/