Is there any elegant way to create something like this
<select>
<option value="" disabled selected>Select your option</option>
<option value="1">Option1</option>
</select>
using @Html.DropDownListFor helper in ASP.NET MVC 4?
Is there any elegant way to create something like this
<select>
<option value="" disabled selected>Select your option</option>
<option value="1">Option1</option>
</select>
using @Html.DropDownListFor helper in ASP.NET MVC 4?
Unfortunately not. There is no way to add attributes to a SelectListItem, which is what gets rendered as an <option>.
You would need to extend the SelectListItem class, and then extend the DropDownListFor to use it. It is unfortunately not very straightforward... It would have been nice for there to be an Attributes dictionary on SelectListItem for this purpose.
Here is an implementation of a custom attribute being applied:
Here's one way you could do it using tag helpers.
<select asp-for="@Model.Orders.FruitsId" class="form-control">
<option value="">Select a Fruit</option>
@foreach (var Fruit in Model.Fruits )
{
if (barber.Name.Equals("Orange"))
{
<option disabled="disabled" value="@Fruit.Id">@Fruit.Name </option>
}
else
{
<option value="@Fruit.Id">@Fruit.Name </option>
}
}
</select>