且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVC列表强类型查看DropDownListFor不显示当前值

更新时间:2023-02-25 19:18:56

创建自定义的 EditorTemplate 类型的 UserFriendDetails

/Views/Shared/EditorTemplates/UserFriendDetails.cshtml

@model UserFriendDetails
@Html.TextBoxFor(m => m.UserName)
....
@Html.DropDownLstFor(m => m.RelationShipId, (SelectList)ViewData["RelationShipList"])

然后在主视图,通过的SelectList 使用附加视图数据模板

@model IEnumerable<UserFriendDetails>
....
@Html.EditorFor(m => m, new { RelationShipList = new SelectList(ViewBag.RelationShip,"Id", "Title") })

这将产生正确的名称属性绑定到你的收集,例如:

This will generate the correct name attributes to bind to you collection, for example

<select name="[0].RelationShipId" ..>
<select name="[1].RelationShipId" ..>

和选择的基础上每 RelationShipId 属性的值正确的选项。

and select the correct option based on the value of each RelationShipId property.

附注:我建议你删除新{@id =ddl_+ @ item.UserID,... 并使用默认的 ID 由助手生成的。它不清楚是什么的onchange 属性做什么,但我也建议你使用的非侵入式JavaScript 而不是行为污染您的标记。

Side note: I suggest you remove the new { @id = "ddl_" + @item.UserID,... and use the default id generated by the helper. Its not clear what the onchange attribute is doing but I also suggest you use unobtrusive javascript rather than polluting your markup with behavior.