Can anyone explain why my drop-down list automatically allows multiple selections?
I'm quite new to Net Core and this is the first time I add a drop-down and I'm obvisouly doing something wrong. Everything works technically, the drop-down list is populated and the Model gets the correct data when posting but for some reason the multiple attribute is automatically set for the drop-down list.
View
<select asp-for="@Model.fooForm.CountryRows"
asp-items="@(new SelectList(Model.fooForm.CountryRows,"CountryCode","CountryName"))"
class="form-control">
<option>Please select Country of use</option>
</select>
ViewModel
namespace foo.Models.ViewModels
{
[Bind(Prefix = nameof(fooIndexRootVM.fooForm))]
public class fooVM
{
public fooVM()
{
}
public fooVM(CountryVM[] countryRows)
{
CountryRows = countryRows;
}
[Display(Name = "Country of use")]
public virtual CountryVM[] CountryRows { get; set; }
}
}
Controller/Service
public async Task<fooIndexRootVM> GetCountries()
{
var countryRows = await fooContext.Country
.OrderBy(c => c.CountryCode)
.Select(c => new CountryVM
{
CountryCode = c.CountryCode
,CountryName = c.CountryName
,CountryBlocked = c.CountryBlocked
})
.ToArrayAsync();
return new fooIndexRootVM
{
fooForm = new fooVM(countryRows)
};
}
From MSDN: The select tag helper
The Select Tag Helper will automatically generate the multiple = "multiple" attribute if the property specified in the asp-for attribute is an IEnumerable.
So in your case the model it's looking at represents a list for asp-for="@Model.fooForm.CountryRows"
.
In order to fix this you can add new property for selected country to model
public virtual CountryVM SelectedCountry { get; set; }
Then asp-for
should be like this:
<select asp-for="@Model.fooForm.SelectedCountry"
asp-items="@(new SelectList(Model.fooForm.CountryRows,"CountryCode","CountryName"))"
class="form-control">
<option>Please select Country of use</option>
</select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.