【发布时间】:2017-01-06 22:42:45
【问题描述】:
我需要在视图上显示一个 DropDownList,其中包含 2 个不同表的值。
- 合作伙伴
- 服务提供者
获取编辑
var partners = db.Partners.Include(p => p.Company);
var serviceProviders = db.ServiceProvider.Include(f => f.Building);
ViewBag.Assigned = new Dictionary<string, string>();
foreach (var p in partners)
{
ViewBag.Assigned.Add("P_" + p.PartnerID.ToString(), p.Name);
}
foreach (var f in serviceProviders)
{
ViewBag.Assigned.Add("FS_" + f.ServiceProviderID.ToString(), f.Name);
}
此字典将包含如下所示的键值对:
- “P_1”、“Abc”
- “P_2”、“Def”
- “SP_1”、“Ghi”
- “SP_2”、“Jkl”
- “SP_3”“Mno”
发布编辑
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ReqID,State,Title,Description,Emission,Severity,BuildingID,Appointment,CUICreator,Photo1,Photo2,Photo3,Photo4,Photo5,IDPartner,IDServiceProvider,IDColaborator,Assigned")] Req req)
{
if (ModelState.IsValid)
{
db.Entry(req).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.EdificioID = new SelectList(db.Buildings, "BuildingID", "Name", req.BuildingID);
return View(req);
}
在我的 Edit.cshtml 上,我尝试了:
@Html.DropDownListFor(model => model.Assigned, new SelectList(ViewBag.Assigned, "Key", "Value"), htmlAttributes: new { @class = "form-control" })
和
@Html.DropDownList("Atribuido", new SelectList(ViewBag.Atribuidos, "Key", "Value"))
他们都给出了同样的错误:
O valor não pode ser nulo.
Nome do parâmetro: items
Descrição: Exceção não processada ao executar o pedido Web atual. Consulte o rastreio da pilha para obter mais informações sobre o erro e o respetivo ponto de origem no código.
翻译成这样:
Value can not be null.
Parameter name: items
Description: Unhandled exception while executing the current Web request. See the stack trace for more information about the error and its source point in the code.
完成这项任务的最佳方法是什么?
【问题讨论】:
标签: dictionary razor html.dropdownlistfor asp.net-mvc-5 dropdownlistfor