NoWar
NoWar

Reputation: 37633

Select First Item in Dropdown List

I just want to select the first item by default but the drop down list has a blank item selected.

How I can resolve it? Thank you!

[Authorize]
public ActionResult Add()
{
   var sportList = new SelectList(db.Sports.OrderBy(s => s.Name).ToList(), "ID", "Name");

   UserTournamentModel m = new UserTournamentModel();
   m.SportList = sportList;
   m.SportID = Guid.Parse(sportList.FirstOrDefault().Value);

   return View(m);
}

and here

<div class="editor-label" style="width: 70px;">
    @Html.DropDownListFor(x => x.SportID, Model.SportList)
</div>

Upvotes: 1

Views: 3968

Answers (1)

M.Babcock
M.Babcock

Reputation: 18965

Use the SelectList constructor overload that accepts the selected item:

var orderedSportList = db.Sports.OrderBy(s => s.Name);
var sportList = new SelectList(orderedSportList.ToList(), "ID", "Name",
     orderedSportList.FirstOrDefault());

Upvotes: 5

Related Questions