2

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.

Dijkgraaf
  • 11,049
  • 17
  • 42
  • 54
  • Are you certain that `Model.Category.Id` holds a value? and if so, that it holds a value which is inside `ViewBag.ListingCategories` ? I suggest you post here more of your view code. – ilans Jun 11 '15 at 05:39

1 Answers1

0

See this answer (by @Elad Lachmi):

SelectListItem has a Selected property. If you are creating the SelectListItems dynamiclly, you can just set the one you want as Selected = true and it will be the default.

SelectListItem defaultItem = new SelectListItem()
{
   Value = 1,
   Text = "Deafult Item",
   Selected = true
};
Community
  • 1
  • 1
ilans
  • 2,537
  • 1
  • 28
  • 29