8

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/

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

It actually does have 'Disabled' property and 'Selected', at least in .net 5, but Hidden is not there unfortunately
2

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>

Comments

1

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');"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.