Friday, December 9, 2011

make a multi-select dropdown based on an enum

<select id="Status" name="OrderFilter.Statuses" multiple="multiple">

   @foreach (var enumValue in Enum.GetValues(typeof(OrderStatusCode)))

   {

      var hint = ((int) enumValue);

      var name = ((OrderStatusCode)enumValue);

      <option value="@hint"

         @if(statuses.Contains(hint)) {

            @:selected

         }

      >@name</option>

   }

</select>

 
 

In this example statuses would be something predefined earlier in the Razor markup. For simplicity sake, one could think of it like so:

@{ int[] statuses = new int[]{3,7}; }

 
 

Note the use of @: which is called the pig operator.

 
 

What follows the pig operator will behave as if wrapped in <text></text>

No comments:

Post a Comment