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?
http://jsfiddle.net/wLAt8/
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:
Adding html class tag under <option> in Html.DropDownList
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>
After struggling I've done this via js function:
function handleSubAction(select) {
var item = document.getElementById(select);
item.children[0].disabled = true;
item.children[0].hidden= true;
return false;
}
and event handler in HTML:
<body onload="handleSubAction('subAction');"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With