BattlFrog
BattlFrog

Reputation: 3397

Trouble setting selected value of strongly typed MVC SelectList

Get the data from the database and tack on the option I plan to be the default selected:

    public List<Forester> GetForesters()
    {
        var data = _db.tblForester.ToList();

        List<Forester> ForesterList = new List<Forester>();

        foreach (var item in data)
        {
            Person person = new Person()
            {
                Key_ = item.Key_,
                FirstName = item.FirstName,
                LastName = item.LastName,
                District = item.District,
                County = item.County
            };
            PersonList.Add(person);
        }
        PersonList.Add(new Person { Key_ = -1, FirstName = "- Select ", LastName = "Person -" } );
        return PersonList;
    }

Model has two properties:

    public int SelectedPersonId { get; set; }
    public IEnumerable<SelectListItem> PersonList { get; set; }

Controller gets the list from the database and makes a selectlist:

        vm.SelectedPersonId = -1;
        vm.PersonList = new SelectList(repo.GetPeople(), "Key_", "PersonsName", vm.SelectedpersonId);

I have tried a couple ways in the view:

                @Html.DropDownListFor(m => m.Key_, new SelectList( Model.PersonList, "Value", "Text", -1), new { @class = "form-control ddl" })

The dropdown works great, except the selected value is the just the first on the list, not the one I specify.

Here is how the HTML renders:

<form action="/Forester/Activity" method="post"><select class="form-control ddl" data-val="true" data-val-number="The field Key_ must be a number." data-val-required="The Key_ field is required." id="Key_" name="Key_"><option value="1">DIANE PARTRIDGE</option>
<option value="2">GARY GROTH</option>

...

The one I added is at the bottom:

<option value="-1">- Select   Forester -</option>

Upvotes: 1

Views: 171

Answers (2)

hutchonoid
hutchonoid

Reputation: 33306

If you use the following, the last parameter specifies the initial text (option label) so you will not need to use a dummy -1 value:

 Html.DropDownListFor(m => m.SelectedPersonId, 
          Model.PersonList as List<SelectListItem>, "Select   Forester -"})

SelectExtensions

Upvotes: 1

Alex Art.
Alex Art.

Reputation: 8781

if you have the following model

 public int SelectedPersonId { get; set; }
 public IEnumerable<SelectListItem> PersonList { get; set; }

you should use

 @Html.DropDownListFor(m => m.SelectedPersonId , Model.PersonList, new { @class = "form-control ddl" })

DropDownListFor helper will evaluate SelectedPersonId and it will try to select it

Upvotes: 1

Related Questions