Using unobtrusive validation, if I simply do @Html.DropDownListFor (or any other xxxFor) then MVC pops in the appropriate client side validation attributes from my model.
However I need a solution where each option has a specific data-custom-attribute adding to it. So to do this, I use a foreach and just manually render the HTML.
By doing so though, I lose the validation. I am not sure if it's possible to add this myself, without hard-coding it, such that it's still based off the data annotations on the model.
Ultimately, I want a dropdownlist bound to my ViewBag.ListOfItems using key/value as the value/text and a data-custom-attribute containing another value taken from the ListOfItems, with whatever model validation is on the model (in this instance, [Required], but I will re-use this code and there may be other attributes).
Is this possible?
Keep the foreach, but use the SelectTagHelper:
<select asp-for="Foo">
@foreach (var option in Model.FooOptions)
{
<option value="@option.Value" data-whatever="blah">@option.Text</option>
}
</select>