views:

222

answers:

1

Hi, I have got a task table in my database with a priority field containing an integer value from 1 to 4 as a test. I am using a LINQ to SQL dbml file so I have a task class and I want to be able to display the text value of the priority to the user in my view, as a value in a select list.

I have added the below code to my task class:

 static enum Priorities {
  High = 1,
  Medium = 2,
  Low = 3,
  None = 4
 }

 public String GetPriority {
  get {
   Priorities p = (Priorities)priority;
   return p.ToString();
  }
 }

I want to use the priority in a drop down list and I am unsure how to do this, by first getting a list of the values to put into the select list and then selecting the correct value for the task object :(

I was thinking about doing the below instead and using a dictionary, but if someone has some advice or a better solution that would be very useful, Thanks.

     static IDictionary<string, int> priorityDictionary =
   new Dictionary<string, int>(){
    {"High", 1},
    {"Medium", 2},
    {"Low", 3},
 {"None", 4}
  };

 public static IEnumerable<string> Priorities {
  get { return priorityDictionary.Keys; }
 }
+2  A: 

Since eventually you'll need this as an IEnumerable<SelectListItem>, why not create a lazy-loaded, static property that contains this as the menu?

private static List<SelectListItem> priorities;
public static IEnumerable<SelectListItem> PriorityMenu
{
    get
    {
         if (priorities == null)
         {
             priorities = new List<SelectListItem>();
             foreach (var i in Enum.GetValues(typeof(Priority)))
             {
                 priorities.Add( new SelectListItem
                                 {
                                     Text = Enum.GetName( typeof(Priority), i ),
                                     Value = i.ToString()
                                 });
             }
         }
         return priorities;
    }
}
tvanfosson
Thanks for the great answer. Looks elegant and I have learnt from just seeing it.
Pricey
Since my enum is called Priorities I changed the typeof(Priority) to typeof(Priorities) but other than that this is a nice solution to getting a list of selectlistitems.. I was unaware of the enum class static methods you can use. One question I have is how do you then use the list in a dropdownlist html helper? It seems to call ToString() on each item in the list but since these are SelectListItem's it just gives the name of the object. Thanks again.
Pricey
Never mind I was trying to create a selectlist object as a property of my viewmodel class but the Html.Dropdownlist uses an IEnumerable of selectlistitem where as selectlist does not, so I can pass the result of the above method.
Pricey