我有一个控制器,它为视图提供SelectList
,然后为DropDownLists
呈现多个SelectList
。我现在希望DropDownLists
具有默认选择的不同值。有没有办法做到这一点?
编辑:哦,当然我希望默认的值可以从我的模型中获得,例如Model.Dj1_Id
等。
控制器:
[HttpGet]
public ActionResult EditPartyInfo(int ID)
{
Party prty = db.Partys.Find(ID);
ViewBag.People = new SelectList(db.People, "Id", "Name");
return View(prty);
}
查看:
@model Musa.Models.Party
@using (Html.BeginForm("EditPartyInfo", "Events", FormMethod.Post))
{
@Html.AntiForgeryToken()
<!-- Some text input fields -->
<div class="form-group">
<label for="Dj1_Id">Dj 1</label>
<div class="form-inline">
@Html.DropDownList("Dj1_Id", ViewBag.People as SelectList, String.Empty, new { @class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<div class="form-group">
<label for="Dj2_Id">Dj 2</label>
<div class="form-inline">
@Html.DropDownList("Dj2_Id", ViewBag.People as SelectList, String.Empty, new { @class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<div class="form-group">
<label for="Dj3_Id">Dj 3</label>
<div class="form-inline">
@Html.DropDownList("Dj3_Id", ViewBag.People as SelectList, String.Empty, new { @class = "form-control person-select", style = "width: 50%;" })
</div>
</div>
<input type="submit" class="btn btn-primary" value="Los geht's" />
}
我实际上最终做了:
控制器:
[HttpGet]
public ActionResult EditPartyInfo(int ID)
{
Party prty = db.Partys.Find(ID);
ViewBag.People = db.People;
return View(prty);
}
查看:
/*...*/
@Html.DropDownList("Dj1_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj1_Id), String.Empty, new { @class = "form-control person-select", style = "width: 50%;" })
/*...*/
@Html.DropDownList("Dj2_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj2_Id), String.Empty, new { @class = "form-control person-select", style = "width: 50%;" })
/*...*/
@Html.DropDownList("Dj3_Id", new SelectList(ViewBag.People, "Id", "Name", Model.Dj3_Id), String.Empty, new { @class = "form-control person-select", style = "width: 50%;" })
答案 0 :(得分:1)
请尝试;
而不是
ViewBag.People as SelectList
此;
new SelectList(ViewBag.People, "Id", "Name", "Id value to select")
作为Html.DropDownList
s
答案 1 :(得分:1)
SelectList有一个构造函数,您可以在其中传入所选对象,所以:
new SelectList(db.People, "Id", "Name", db.People.FirstOrDefault(x => x.Id == party.Dj1_Id)
我个人更喜欢使用IEnumerable<SelectListItem>
,如此:
ViewBag.People = db.People.Select(x => new SelectListItem { Text = x.Name, Value = x.Id, Selected = x.Id == party.Dj1_Id);
无论哪种方式都应该有效。