我建立了一个新的SelectListItem。我可以填充选项,但不会让我设置“选定项”:
模型值
Model.Clients.ClientId = 1
Model.Clients.Name = "Company 1"
Model.Clients.ClientId = 2
Model.Clients.Name = "Company 2"
Model.Clients.ClientId = 3
Model.Clients.Name = "Company 3"
Model.Clients.ClientId = 4
Model.Clients.Name = "Company 4"
Model.Clients.ClientId = 5
Model.Clients.Name = "Company 5"
Model.User.Client.ClientId = 3
DropDownListFor
@Html.DropDownListFor(model => model.User.Client, Model.Clients.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.ClientId.ToString(),
Selected = x.ClientId == Model.User.Client.ClientId
}).ToList(),
new { @class = "form-control" }
)
下拉列表HTML
<select class="form-control" id="User_Client" name="User.Client">
<option value="1">Company 1</option>
<option value="2">Company 2</option>
<option value="3">Company 3</option>
<option value="4">Company 4</option>
<option value="5">Company 5</option>
</select>
我的代码应将选项3选中,但不是。
试试下面的代码:
@Html.DropDownListFor(model => model.User.Client.ClientId,
new SelectList(Model.Clients,"ClientId","Name", Model.User.Client.ClientId),
new { @class = "form-control" })
注意:您不能Client
为DropDownList绑定类,您需要使用属性ClientId
。
最好为所选客户端添加另一个属性。如下所示:
public class yourModel
{
public int selectedClientId {get;set;}
//
}
@Html.DropDownListFor(model => model.selectedClientId,
new SelectList(Model.Clients,"ClientId","Name", Model.User.Client.ClientId),
new { @class = "form-control" })
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句