Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple selection from asp.net core application

I have List<SelectListItem> variable with two values. I want to represent it as dropdown box in html so I'm doing like this.

<div class="form-group row">
    <label asp-for="Roles" class="col-sm-2 col-sm-offset-2 form-control-label"></label>
    <div class="col-md-6">
        <select asp-for="Roles" asp-items="@Model.Roles" class="form-control selectpicker bs-select-hidden"></select>
    </div>           
</div>

and this code shows me the list with those two items, but it also generates

multiple="multiple"

attribute for select tag.

How can I make not to generate multiple attribute?

like image 521
Nikas Žalias Avatar asked Jul 15 '26 08:07

Nikas Žalias


1 Answers

The Select Tag Helper automatically makes the select element multiple if your asp-for property is an IEnumerable. The way to avoid that is to use your base class (not a collection) as the asp-for property. The asp-items property should still be a collection since these are the items that will become options in the select list.

In your example this is simply changing your asp-for="Roles" to asp-for="Role"

<div class="form-group row">
<label asp-for="Roles" class="col-sm-2 col-sm-offset-2 form-control-label"></label>
<div class="col-md-6">
    <select asp-for="Role" asp-items="@Model.Roles" class="form-control selectpicker bs-select-hidden"></select>
</div>           

You may need to adjust your view model being passed to the view so that it has access to the base class Role, as well as the collection of Roles to be enumerated

ASP NET Core Select Tag Helper Reference

like image 174
plumdog Avatar answered Jul 18 '26 01:07

plumdog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!