Mesajlar Etiketlendi ‘dropdownlist’

Hello everyone, i am working on a system which needs to set Dropdownlist with values. So i looked net for some solution but i couldn’t find something which solve my problem. So i kept diggin’ , at last i realize something with ViewBag property.

lets look our scenario;

We have some selectList items that we took from DB.

var categories = db.categories.Select(c => new {c.id,c.name}); // We took data from db.

ViewBag.categories = new SelectList(categories.AsEnumerable(),”id”,”name”) // we set ViewBag items

try to call from View,

  @Html.DropDownList(“categories”, (IEnumerable<SelectListItem>)ViewBag.categories, new { @class = “form-control” })  //cool it’s working

but if you want to edit product on View you cannot see actual selected category;) in this situation i found if ViewBag name after “.” can not be same as variable name;) so after change had made, code look like this;

//In Controller

 

var categorie = db.categories.Select(c => new {c.id,c.name}); // We took data from db and changed name of categories to categorie 😉

ViewBag.categories = new SelectList(categorie.AsEnumerable(),”id”,”name”,Model.selectedCategorieId) // we set ViewBag items

 

//In View

 

@Html.DropDownList(“categorie“, (IEnumerable<SelectListItem>)ViewBag.categories, new { @class = “form-control” })  //cool it’s working

 

 

That’s it 😉 it will take us full of category items with selected value 😉 Happy codin’ 😉