Add attribute to select list option

Ciarán Bruen picture Ciarán Bruen · Jul 1, 2012 · Viewed 31.7k times · Source

I have a list of items in a drop down list within a Razor view. In the database each item has 3 values associated with it - the database id, short name (for display), and long name (for passing to a service). The drop down must show the short name, so I'm populating the drop down with the database id as the value and the short name as the text.

However when a user selects an item I need pass the long name as a query parameter to a search service using jQuery, e.g when Cortina is seleted "Ford Cortina 1979 Blue" needs to be passed to the service. My first thought is store the long name as a data dash attribute but I'm wondering is there a better way. So

  • How do I store all 3 values in the drop down list?
  • If I do use data dash attributes how do I incorporate all the LONG_NAME values into Html.DropDownListFor or somehow add them to the drop down list?

DB:

CARID SHORT_NAME LONG_NAME
1     Viper     Dodge Viper 1982
2     Boxster   Porsche Boxster 2009 Black
3     Cortina   Ford Cortina 1979 Blue

Controller helper to create the drop down:

public static IEnumerable<SelectListItem> GetSelectList(this IEFRepository repository, string typeName)
{
    var vehicle = repository.TypeTypes.FirstOrDefault(t => t.Name.ToUpper() == typeName);
    if (vehicle != null)
    {
        var carList = vehicle.SubTypes.ToList().OrderBy(s => s.Name);
        var selectList = new SelectList(subTypeList, "SubTypeID", "Name");

        return selectList;
    }
}

Here's the code I use to create the drop down:

<div class="editor-field">
    @Html.DropDownListFor(model => model.CarID,
        new SelectList(ViewBag.Cars, "Value", "Text", "1"))
    @Html.ValidationMessageFor(model => model.CarShortName)
</div>

Here's the output:

<select id="CarID" name="CarID" data-val="true" data-val-number="The field CarID must be a number." data-val-required="The CarID field is required.">
    <option value="2">Boxster</option>
    <option value="3">Cortina</option>
    <option selected="selected" value="1">Viper</option>
</select>

Answer

drzaus picture drzaus · Jan 28, 2013

Everyone forgets the "classic" way to solve these problems: use a foreach loop and actually write the input html. Only downside is you have to add the automatic attribute stuff (like validation, etc), which depending on your purpose may not be a big deal.

Something like:

<select> // add other attributes as expected
@foreach(var type in Model.MyFancyTypes) {
<option value="@type.SubTypeID" data-description="@type.Description" 
    @if(ViewBag.TypeSelected == type.SubTypeID) {
        selected="selected"
    }>@type.Name</option>
}
</select>