The Viewdata item that has the key 'officeId' is of type 'System.String' but must be of type 'Ienumerable<Selectlistitem>'

Asked

Viewed 232 times

-2

Controller:

 public ActionResult Cadastrar()
    {

        ViewBag.officelist = new SelectList(new OfficeREP().ListarTodos(),
           "id",
           "estado"
       );

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Cadastrar(OpportunityMOD opportunidade)
    {

        if (ModelState.IsValid)
        {
            var opportunity01 = new OpportunityREP();
            opportunity01.Salvar(opportunidade);
            TempData["mensagem"] = "Cadastro realizado com Sucesso!";
            return RedirectToAction("Index");
        }

        return View(opportunidade);

    }

Model

    [DisplayName("Escritório")]
    public string officeId { get; set; }

View

                <div class="col-md-2">
                @Html.LabelFor(model => model.officeId)
                @Html.DropDownListFor(model => model.officeId,(SelectList)ViewBag.officeList, string.Empty, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.officeId, "", new { @class = "text-danger" })
  • The funny thing that was working normal, now stopped and accuses this mistake... I do not understand what happened. It normal list when recording it gives this error.

  • Removes this line @Html.Dropdownlistfor(model => model.officeId,(Selectlist)Viewbag.officeList, string.Empty, new { @class = "form-control" })

  • I took it, but there’s no list, okay.

  • So, you’re trying to generate a LIST of a STRING, that’s the problem

  • Okay, more like I’ll list the objects and write as a string in the database. Because before it listed and writes, you know tell me ?

  • List a list and not a string

  • Still unsuccessful.

  • As you have listed?

Show 4 more comments

1 answer

1

Hello,

The problem is that you are trying to list a string.

In this line.

@Html.DropDownListFor(model => model.officeId,(SelectList)ViewBag.officeList, string.Empty, new { @class = "form-control" }) 

Then do it like this

Model

[DisplayName("Escritório")]
    public IEnumerable<SelectListItem> officeId { get; set; }

Controller

ViewBag.officelist = new SelectList(new OfficeREP().ListarTodos(), 
"id", 
"estado" 
);

View

@Html.DropDownListFor(model => model.officeId,(SelectList)ViewBag.officeList, string.Empty, new { @class = "form-control" })

Browser other questions tagged

You are not signed in. Login or sign up in order to post.