I have a DropDownList
which I populate like below:
Controller
IEnumerable<Category> categories = _db.Category.ToList();
var selectList = _db.Category.Select(i => new SelectListItem()
{
Text = i.Name,
Value = i.Id.ToString()
});
ViewBag.categoriesSelectList = selectList;
And use in view like so:
<select asp-for="Category" name="categoryID" asp-items="@ViewBag.categoriesSelectList" >
<option>Vælg Kategori:</option>
</select>
However, I can't seem to figure out how I can set the already selected value, so the dropdown "starts" on that value. I tried enumerating over the selectList
and changing the Selected
attribute of the SelectListItem
, but it doesn't work since it won't save the changes I make.
Hope my question makes sense :) thanks all.
CodePudding user response:
Option 1:
Modify your code to include Selected
property when creating list of SelectListItem
items:
var selectList = _db.Category.Select(i => new SelectListItem()
{
Text = i.Name,
Value = i.Id.ToString(),
Selected = /* Some condition that is true when the current item should be selected */
});
Option 2:
Define a view model with structure that might be referenced in the <select>
tag:
public class SelectViewModel
{
public string Category { get; set; }
public List<SelectListItem> Categories { get; set; }
}
The action method:
public IActionResult Categories()
{
var model = new SelectViewModel() ;
model.Categories = _db.Category.Select(i => new SelectListItem()
{
Text = i.Name,
Value = i.Id.ToString()
});
model.Category = ... your_code_to_set_default_selection;
return View(model);
}
The view:
@model SelectViewModel
<select asp-for="Category" asp-items="@Model.Categories"></select>
Can find some mode information in the documentation: The Select Tag Helper