我在部分视图中有一个dropdownlistFor
<div class="col-md-12">
Referre To: @Html.DropDownListFor(m => m.SenderPosition_Id, ViewBag.senderPositionsList as SelectList, "--Select--", new { @class = "form-control" })
</div>
此Dropdownlistfor填充在控制器中,如下所示:
List<ReferrableUsersViewModel> senderPositionsList = new List<ReferrableUsersViewModel>();
using (WebECartableEntities dc = new WebECartableEntities())
{
senderPositionsList = dc.Positions.Where(m => m.usr_Id == User.Identity.Name).Select(x => new ReferrableUsersViewModel
{
SenderPosition_Id = x.ID,
Name_Position = x.Title
}
).Distinct().OrderBy(m => m.Name_Position).ToList();
ViewBag.senderPositionsList = new SelectList(senderPositionsList, "SenderPosition_Id", "Name_Position");
}
我想要DropdownlistFor有一个项目,它会被自动选择,但是如果有多个项目,则让用户选择它。 我该如何在MVC中做到这一点?
答案 0 :(得分:1)
在控制器操作中,您可以检查集合的计数是否为1,将模型对象的SenderPosition_Id
设置为该对象,例如:
if(senderPositionsList.Count == 1)
{
model.SenderPosition_Id = senderPositionsList.First().ID;
}
......
......
return View(model);