I've been trying to create a drop down list with asp tag helpers and for some reason they always look strange. I'll include my code for Controller, View, and view model. Also the picture of how it looks. Controller:
public async Task<IActionResult> Create()
{
var dalias = await _context.DeptAliases
.Select(m => new SelectListItem { Text = m.Alias, Value = m.DeptAliasPkey.ToString() }).Distinct()
.ToListAsync();
var vm = new CopyCenterCreateViewModel()
{
DAlias = dalias,
};
return View(vm);
}
View:
@model PrintShop.ViewModels.CopyCenterCreateViewModel
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" ></div>
<label asp-for="DAlias" ></label>
<select asp-for="DAlias" asp-items="Model.DAlias" ></select>
<span asp-validation-for="DAlias" ></span>
</form>
ViewModel:
public class CopyCenterCreateViewModel
{
public List<SelectListItem> DAlias { get; set; }
}
CodePudding user response:
It looks like the select
control is rendering in multi-selection mode. If the tag helper asp-for
is binding to an IEnumerable
then the select
element is rendered in multiple mode.
From tag-helpers multiple select section of the docs:
The Select Tag Helper will automatically generate the
multiple = "multiple"
attribute if the property specified in the asp-for attribute is anIEnumerable
.
You only have a single property in the ViewModel which is a List
, and you're binding the items to the same property as the selected value.
You could rename the list of items to something else and add a property to bind to the value of the selected item:
public class CopyCenterCreateViewModel
{
public string DAlias { get; set; }
public List<SelectListItem> Items { get; set; }
}
In the controller you'd populate the Items
property of the CopyCenterCreateViewModel
.
In the view bind asp-items
to the view model Items
property:
<select asp-for="DAlias" asp-items="Model.Items" ></select>