MVC DropDownList with Dictionary

1.1k views Asked by At

I need to display a DropDownList on my view, with the values of 2 different tables.

  • Partner
  • ServiceProvider

GET Edit

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);
            }

This Dictionary will hold key,value pairs that look like this:

  • "P_1", "Abc"
  • "P_2", "Def"
  • "SP_1", "Ghi"
  • "SP_2", "Jkl"
  • "SP_3" "Mno"

POST Edit

        [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);
        }

On my Edit.cshtml, I tryed:

@Html.DropDownListFor(model => model.Assigned, new SelectList(ViewBag.Assigned, "Key", "Value"), htmlAttributes: new { @class = "form-control" })

and

@Html.DropDownList("Atribuido", new SelectList(ViewBag.Atribuidos, "Key", "Value"))

and both of them give the same error:

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.

which translates to this:

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.

What would be the best way to do this task?

1

There are 1 answers

0
D Stanley On

That error message matches the message you'd get from an ArgumentNullException which is thrown when a method gets a null value for a required argument. I suspect the error is coming from the SelectList constructor since it takes a parameter named items. Since you don't set ViewBag.Assigned in your Post handler, the viewbag item is probabvly getting lost and is null when you try to render the edit view after a post.