Tutorial :Dictionary, enum or other alternative for implementing a priority of a task in MVC?


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; }      }  


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;      }  }  


If you wanted your string representations to be different than their Enum.GetName, while still maintaining type safety, check this out: C# String enums

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »