Selectlist with Viewbag

Asked

Viewed 1,134 times

2

I’m trying to make a SelectList using ViewBag. But when I run my code it shows where the information I’m trying to access is, for example:

NomeProjeto.Models.NomeModel

I’m using the following code in my Controller:

var setores = new List<Setor>();

using (RamaDb db = new RamaDb())
{
     setores = db.Setores.ToList();
}

ViewBag.ID = new SelectList(setores, "setorNome");

And this in my View:

@Html.DropDownListFor(model => model.setores, (IEnumerable<SelectListItem>)ViewBag.ID)

When I run the application on SelectList appears the number of Sectors correctly, type have 3 sectors in my DB then appears 3 options, but in all is written Ramalaguia.Models.Sector

How can I fix this?

1 answer

2


failed to put the field that will appear, you just put the ID, change the line:

ViewBag.ID = new SelectList(setores, "setorNome");

for

ViewBag.ID = new SelectList(setores, "setorID","setorNome");

If you want to send which will be selected is the 4th field, ex:

 ViewBag.ID = new SelectList(setores, "setorID","setorNome", 4);

where 4 would be the setorID Selected

  • Actually the "setorNome" was already the name, and I had the "setorID" but I thought I should only put it if I wanted it to appear. But even so I understood your answer and it really worked. Thanks for the help. I just won’t raise your answer because I don’t have a reputation.

  • the first is ID the second is the text I will edit the answer to get the correction fields

Browser other questions tagged

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