Search code examples
c#asp.net-mvcasp.net-core

Add Selected On Custom SelectListItem


To fill a dropdown in the view with a Selected Item, I can create a SelectList as follows:

ViewData["MyDropDown"] = new SelectList(_context.DataTable, "ItemID", "ItemName", ItemID);

However, I have a dropdown with a custom ListItem that looks as follows:

var dropDownData= await _context.DataTable.Select(u => new SelectListItem { Value = u.ItemID.ToString(), Text = u.ItemName}).ToListAsync();
dropDownData.Add(new SelectListItem() { Value = "", Text = "-- Select -- "});
ViewData["MyDropDown"] = dropDownData;

If I want to make the "-- Select --" option the selected one, I just need to add ", Selected = true" to the line.

Now, how can I specify a Selected Item from the options generated by the _context?

Thanks!


Solution

  • Agreeing with @pcalkin, you can set the Id of the selected customer by default.Then loop through each item in the drop-down list, if the value of an item is equal to the default selected Id, then set the Selected property of this item to true, you can refer to the following example: Controller:

    public IActionResult Index()
    {
         var dropDownData = _context.Customers
          .Select(u => new SelectListItem { Value = u.Id.ToString(), Text = u.Name })
          .ToList();
    
         dropDownData.Add(new SelectListItem() { Value = "", Text = "-- Select -- " });
         var defaultSelectedID = 3;
         foreach (var item in dropDownData)
         {
             if (item.Value == defaultSelectedID.ToString())
             {
                 item.Selected = true;
                 break;
             }
         }
    
         ViewData["MyDropDown"] = dropDownData;
    
         return View();
    }
    

    Page:

    <form method="post" asp-action="Index">
         <select name="SelectedOfficerId">
             @foreach (var item in (List<SelectListItem>)ViewData["MyDropDown"])
             {
                 <!option value="@item.Value" @(item.Selected ? "selected" : "")>@item.Text</!option>
             }
         </select>
         <button type="submit">Submit</button>
    </form>
    

    I set some seed data:

    enter image description here

    The option of default ID will be displayed:

    enter image description here