【问题标题】:MVC DropDownList with Dictionary带有字典的 MVC 下拉列表
【发布时间】: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


    【解决方案1】:

    该错误消息与您从ArgumentNullException 获得的消息相匹配,当方法获得所需参数的空值时会抛出该消息。我怀疑错误来自SelectList constructor,因为它需要一个名为items 的参数。由于您没有在Post 处理程序中设置ViewBag.Assigned,因此当您尝试在发布后呈现编辑视图时,viewbag 项目可能会丢失并且为空。

    【讨论】:

      猜你喜欢
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多