itsmatt
itsmatt

Reputation: 31406

SelectList doesn't show the selected item

This is pared down a bit, but essentially I've got a model that looks something like this:

public class PersonCreateEditViewModel
{
   public string Title { get; set; }

   public IEnumerable<SelectListItem> Titles { get; set; }
}

and on my edit page I want to display the person's current title in a DropDownList so we can change their title. That code looks like this:

@Html.DropDownListFor(model => model.Title, new SelectList(Model.Titles, "Value", "Text", Model.Title))

and I populate it in my action like so by retrieving a bunch of strings:

IEnumerable<SelectList> titles = somelistoftitles.Select(
      c => new SelectListItem
      {
         Value = c,
         Text = c
      };


var viewModel = new PersonCreateEditViewModel()
{
    Title = model.Title,
    Titles = sometitles
};

return View(viewModel);

and this populates the DropDownList with the values but does not select the person's current title. So, I'm obviously doing something wrong here. Looking at the underlying html, I see that the selected attribute is not set for the option corresponding to the person's Title. I thought that specifying Model.Title there as the third argument would select it.

Ideas?


Update

I added the setting of the Selected property as qntmfred suggested below, and that'll set the right one in the list to true but the <option> doesn't have the selected attribute on it.


SOLVED

So, this was subtle. I just so happened to have a ViewBag entry named "Title" - something like this:

@{
    ViewBag.Title = "Edit Person"
}

and this evidently caused the selection to not work since my model has a "Title" property as well. I solved the problem by renaming the property.

Upvotes: 4

Views: 1870

Answers (2)

itsmatt
itsmatt

Reputation: 31406

SOLVED

As I wrote at the end of my question, this wasn't an obvious thing. I just so happened to have a ViewBag entry named "Title" - something like this:

@{
    ViewBag.Title = "Edit Person"
}

and this evidently caused the selection to not work since my model has a "Title" property as well. I solved the problem by renaming the property.

Way too much time wasted on this problem this morning.

Lesson learned.

Upvotes: 4

kenwarner
kenwarner

Reputation: 29120

You need to set the Selected property on your SelectListItem

IEnumerable<SelectList> titles = somelistoftitles.Select(
      c => new SelectListItem
      {
         Value = c,
         Text = c,
         Selected = (c.Equals(model.Title))
      };

Upvotes: 1

Related Questions