DropDownListFor未从Model中正确选择

时间:2015-08-28 21:56:01

标签: c# asp.net-mvc razor html.dropdownlistfor

<div id="masonry-grid" style="position: relative; width: 1300px; height: 916px;">

<div class="item" style="position: absolute; left: 0px; top: 0px;"></div>
<div class="item" style="position: absolute; left: 325px; top: 0px;"></div>
<div class="item" style="position: absolute; left: 650px; top: 0px;"></div>
<div class="item" style="position: absolute; left: 975px; top: 0px;"></div>
<div class="item" style="position: absolute; left: 325px; top: 316px;"></div>
<div class="item" style="position: absolute; left: 650px; top: 406px;"></div>
<div class="item" style="position: absolute; left: 975px; top: 423px;"></div>
<div class="item" style="position: absolute; left: 0px; top: 442px;"></div>
<div class="item"></div>
<div class="item"></div>

所以我的列表正在创建,@Html.DropDownListFor(model => model.Members[index].Contact.RelationId.Value, new SelectList(Model.Relations, "RelationId", "Description"), new { @class = "form-control" }) 但是不会只选择第一个DDL的第二个ID。

enter image description here enter image description here

我已经尝试了几种不同的方式和堆栈溢出解决方案。不确定我可能做错了什么

one of the answers attempted

model.Members[index].Contact.RelationId.Value = 2

没有效果

2 个答案:

答案 0 :(得分:1)

在这一行

@Html.DropDownListFor(model => model.Members[index].Contact.RelationId.Value, new SelectList(Model.Relations, "RelationId", "Description"),  Model.Members[index].Contact.RelationId.Value)

应该是这样的:

@Html.DropDownListFor(m => m.Members[4].Contact.RelationId.RelationId, 
new SelectList(Model.Relations, "RelationId", "Description", Model.Members[4].Contact.RelationId.RelationId), new { @class = "form-control" })        

“m =&gt; m.Members [4] .Contact.RelationId.RelationId”是回发期间应保存的值。

Model.Members [4] .Contact.RelationId.RelationId是下拉列表中的选定值。

答案 1 :(得分:0)

根据MSDN上的this article,SelectList类上有一个构造函数,它接受以下参数:

SelectList Constructor (IEnumerable, String, String, Object)

在IEnumerable是SelectList项的情况下,第一个String是键,第二个String是文本,而Object是SelectedValue,这是我看到的目标。

因此,我相信你应该试试这个:

@Html.DropDownListFor(model => model.Members[index].Contact.RelationId.Value, new SelectList(Model.Relations, "RelationId", "Description", model.Members[index].Contact.RelationId.Value), new { @class = "form-control" })

看看它是否有效:)

相关问题