我正在創建多選列表框。我能夠成功地將項目從模型渲染到列表框。以下是我的代碼:M-V-C:如何在編輯模式下獲取或指示列表框中的選定項目?
屬性
public IEnumerable<SelectListItem> carTypes { get; set; }
public IEnumerable<string> selectedCarTypes { get; set; }
創建操作
public ActionResult Create()
{
List<SelectListItem> selectListItem = new List<SelectListItem>();
foreach(CarType type in db.CarTypes)
{
SelectListItem item = new SelectListItem()
{
Text = type.Name,
Value = type.Id.ToString()
};
selectListItem.Add(item);
}
Assigning assign = new Assigning();
assign.carTypes = selectListItem;
return View(assign);
}
查看
@Html.ListBoxFor(model=>model.selectedCarTypes,Model.carTypes)
ŧ他的問題是編輯行爲。我一直試圖突出顯示Edit View
中的所有列表框,這些列表框是爲特定的AssignId
選擇的。在列表框中有三個項目:現代,豐田和寶馬,我選擇寶馬和豐田和創建分配。現在,當我回到編輯視圖時,它應該突出顯示寶馬和豐田。
我參考了here,但沒有爲我工作。有沒有解決這個問題的方法?
修改:這是我Edit Action
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Assigning assign = db.Assigning.Find(id);
if (assign == null)
{
return HttpNotFound();
}
return View(assign);
}
發表您的編輯方法
List<string>
。 – User3250完成。現在請檢查請 –
你在Edit action中添加'carTypes'在哪裏?您需要在編輯時爲選定的車型設置爲「selected = true」。 – User3250