[RESOLVED]EnumDropDownListFor

How to get the selected value in EnumDropDownListFor?

@Html.EnumDropDownListFor(m => m.VehicleType, new { onchange = "enablePassengerCount()" })

I need to get the selected value in the javascript function attached to the onchange event.

The EnumDropDownListFor() helper isn’t really going to react any differently than the traditional DropDownList helper would. If you had the following enum types :

public enum VehicleType
{
        Hovercraft,
        Unicycle,
        Bicycle,
        Car,
        Truck,
        Van,
        Tank,
        Hanglider,
        Airplane,
        Blimp
}

And bound it to your EnumDropDownListFor() as seen below (using ‘this’ as a parameter will make it easier to access values from the element itself) :

@Html.EnumDropDownListFor(m => m.Type, new { onchange = "enablePassengerCount(this);" })

It would generate the following markup :

<select data-val="true" data-val-required="The Type field is required." id="Type" name="Type" onchange="enablePassengerCount()">
    <option selected="selected" value="0">Hovercraft</option>
    <option value="1">Unicycle</option>
    <option value="2">Bicycle</option>
    <option value="3">Car</option>
    <option value="4">Truck</option>
    <option value="5">Van</option>
    <option value="6">Tank</option>
    <option value="7">Hanglider</option>
    <option value="8">Airplane</option>
    <option value="9">Blimp</option>
</select>

Combining all of this, you can get either the selected value or selected text properties purely through Javascript using :

<script type="text/javascript">
        function enablePassengerCount(source) {
            // Get the value that is selected
            var selectedValue = source.value;
            // Get the text of the selected value
            var selectedText = source.options[source.value].innerHTML; 
        }
</script>

On a side note you may find this useful if you make frequent use of enums.

http://geeksharp.com/2011/11/02/power-up-your-enumerations/

Leave a Reply