Skip to content

Instantly share code, notes, and snippets.

@andrewbranch
Last active August 29, 2015 13:57
Show Gist options
  • Save andrewbranch/9628142 to your computer and use it in GitHub Desktop.
Save andrewbranch/9628142 to your computer and use it in GitHub Desktop.
Make enums available in JavaScript
// Drop ModelWithEnum.ThingTypeDictionary into a ViewModel that gets serialized to JSON
// for handy, scalable use of enums in JavaScript. For example, you can change
//
//
// if (m.ThingTypeId === 3)
//
// to
//
// if (m.ThingTypeId === model.ThingTypeDictionary.Spaceship)
namespace App.Models {
public class ModelWithEnum {
public TypeOfThing ThingTypeId { get; set; }
public static Dictionary<string, int> ThingTypeDictionary = Enum.GetValues(typeof(TypeOfThing)).Cast<int>().ToDictionary(t => Enum.GetName(typeof(TypeOfThing), t), t => t);
}
public enum TypeOfThing {
Foo = 1,
Bar = 2,
Spaceship = 3,
Submarine = 4
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment