Note that there are some explanatory texts on larger screens.

plurals
  1. POAdd attribute to select list option
    primarykey
    data
    text
    <p>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.</p> <p>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</p> <ul> <li>How do I store all 3 values in the drop down list? </li> <li>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?</li> </ul> <p>DB:</p> <pre><code>CARID SHORT_NAME LONG_NAME 1 Viper Dodge Viper 1982 2 Boxster Porsche Boxster 2009 Black 3 Cortina Ford Cortina 1979 Blue </code></pre> <p>Controller helper to create the drop down:</p> <pre><code>public static IEnumerable&lt;SelectListItem&gt; GetSelectList(this IEFRepository repository, string typeName) { var vehicle = repository.TypeTypes.FirstOrDefault(t =&gt; t.Name.ToUpper() == typeName); if (vehicle != null) { var carList = vehicle.SubTypes.ToList().OrderBy(s =&gt; s.Name); var selectList = new SelectList(subTypeList, "SubTypeID", "Name"); return selectList; } } </code></pre> <p>Here's the code I use to create the drop down:</p> <pre><code>&lt;div class="editor-field"&gt; @Html.DropDownListFor(model =&gt; model.CarID, new SelectList(ViewBag.Cars, "Value", "Text", "1")) @Html.ValidationMessageFor(model =&gt; model.CarShortName) &lt;/div&gt; </code></pre> <p>Here's the output:</p> <pre><code>&lt;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."&gt; &lt;option value="2"&gt;Boxster&lt;/option&gt; &lt;option value="3"&gt;Cortina&lt;/option&gt; &lt;option selected="selected" value="1"&gt;Viper&lt;/option&gt; &lt;/select&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload