SelectList does not display the selected item

This has been reduced a bit, but essentially I have 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 current name of the person in DropDownList so that we can change the name. This code is as follows:

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

and I fill it in my action like this, getting a bunch of lines:

 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 DropDownList with values, but does not select the current user. So, I'm obviously doing something wrong. If you look at the basic html, I see that the selected attribute is not set for the parameter corresponding to the Title person. I thought I would specify Model.Title where the third argument would select it.

Ideas?


Update

I added the setting of the selected property as qntmfred, proposed below, and this will set the list to true, but <option> does not have the selected attribute on it.


solvable

So that was subtle. I just got a ViewBag entry titled β€œTitle” - something like this:

 @{ ViewBag.Title = "Edit Person" } 

and this, obviously, made the choice not work, since my model also has the Title property. I solved the problem by renaming the property.

+4
source share
2 answers

solvable

As I wrote at the end of my question, this was not obvious. It so happened that there is a ViewBag entry with the title β€œHeading” - something like this:

 @{ ViewBag.Title = "Edit Person" } 

and this, obviously, made the choice not work, since my model also has the Title property. I solved the problem by renaming the property.

Too much time was spent on this problem this morning.

Lesson learned.

+4
source

You need to set the Selected property to SelectListItem

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

Source: https://habr.com/ru/post/1387411/


All Articles