Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc dropdownlist option disabled selected

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/

like image 907
Sergey Malyutin Avatar asked Mar 01 '14 20:03

Sergey Malyutin


3 Answers

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

like image 98
Mister Epic Avatar answered Sep 28 '22 07:09

Mister Epic


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>
like image 21
Ahmed Bashir Avatar answered Sep 28 '22 06:09

Ahmed Bashir


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');"/>
like image 30
Jeka Developer Avatar answered Sep 28 '22 07:09

Jeka Developer