1

I'm trying to create a dropdown list (using bootstrap-select) with different data-subtext attributes on each option. The thing is, when I use tag helper, it automatically creates validation tags (which is great) but forbids me from using any data-* attributes on select list options.

Creating options with loop like this disables client-side validation:

<select name="@Html.NameFor(model => Model.SelectedRoles)" id="@Html.IdFor(model => Model.SelectedRoles)" class="form-control selectpicker" data-live-search="true" autocomplete="off" data-size="8" multiple>
@foreach (var role in Model.RolesSelectListItems)
{
    <option data-subtext="@role.Description" value="@role.Id">@role.Code</option>
}
</select>

Creating list like this will not allow to use data-attributes:

@Html.DropDownListFor(x => Model.SelectedRoles, new SelectList(Model.RolesSelectListItems, nameof(RoleViewModel.Id), nameof(RoleViewModel.Code)),
            new { @class = "form-control selectpicker", @data_live_search = "true", @autocomplete = "off", @data_size = "8", @multiple = "" })

My viewmodel is like this:

public IEnumerable<RoleViewModel> RolesSelectListItems { get; set; }

[Display(Name = "Requested roles")]
[Required(ErrorMessage = "Select at least one role")]
public IEnumerable<int> SelectedRoles { get; set; }

Is it possible to maybe extend Html.DropDownListFor somehow, so it will add data-subtext for each option using desired property value? I'd like to have both automatically created validation tags and data attributes, if possible.

Ilya Bezus
  • 140
  • 10

0 Answers0