I've been working on this for 2 days and I can't make it work. I'm trying to make a DropDownListFor with a default value (Like in an Edit page). I made it work without a model but when there is a model, it shows the first item as the default not the one I wanted. I tried adding a Selected = true in a SelectListItem while being in a foreach loop like this, still not working:
List<SelectListItem> selectListCategories = new List<SelectListItem>();
foreach(var item in listCategories)
{
if(item.Id == Model.Category.Id)
{
selectListCategories.Add(new SelectListItem { Value = item.Id.ToString(), Text = item.Name, Selected=true });
}
else
{
selectListCategories.Add(new SelectListItem { Value = item.Id.ToString(), Text = item.Name });
}
}
This one worked but without a model.
I also tried adding a default value in the SelectList object like that :
@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.ListingCategories, "Id", "Name", Model.Category.Id))
It either didn't work or there is something I didn't understand correctly because I tried adapting some example I saw here and on msdn posts without any success.
ViewBag.ListingCategories
contains a IEnumerable list of my categories taken from my database.
Of course, Model.Category
contains a Category object with an Id (this is a Foreign Key to another table) and a Name.
Now I'm out of option so hopefully I can find help here.
Thanks.