I’m using Entity Framework Code First (v6.0.2) for my data layer. Enum support was added in v5.0 and .NET 4.5 must be targeted to use enums.
At the time of writing, my version of Breeze (1.4.11) does not provide enum values in the Breeze Metadata.
When editing or creating entities client side using Breeze, I want to fill dropdowns with options from the server side enums. Breeze populates the client side models it creates with string values for each enum property.
This StackOverflow answer shows how to use the Breeze metadata to create global javascript objects on the client:
I use the “options” custom binding provided by the Knockout library to render my option sets, and most of the time I want the value selected by the user to replace the value of an entity column. Ideally I want a sort of associative array indexed by enum name that I can bind to my views. I came up with this utility function that works for me.
1: var getOptionSets = function(enumSchema, optionSets) { 2: var manageOptionSets = function() { 3: var registerOptionSet = function(optionSetName) { 4: optionSets[optionSetName] = ko.observableArray([]); 5: } 6: , addToOptionSet = function(optionSetName, memberName, memberValue) { 7: var optionSet = optionSets[optionSetName]; 8: if (optionSet !== undefined && optionSet !== null) { 9: var newOptionSet = new optionSetValue(memberName, memberValue); 10: optionSet.push(newOptionSet); 11: } 12: } 13: , parseOptionSet = function(optionSet) { 14: registerOptionSet(optionSet.name); 15: $.each(optionSet.member, function(i, m) { 16: addToOptionSet(optionSet.name, m.name, m.value); 17: }); 18: }; 19: return { 20: parseOptionSet: parseOptionSet 21: }; 22: } 23: , optionSetValue = function(typeName, typeValue) { 24: var self = this; 25: self.name = ko.observable(typeName); 26: self.value = ko.observable(typeValue); 27: return self; 28: } 29: , getEnums = function() { 30: // extract all enums 31: ko.utils.arrayForEach(enumSchema, function(c) { 32: manageOptionSets().parseOptionSet(c); 33: }); 34: }; 35: getEnums(); 36: };
I call this from a function in my view model. “optionSets” is just an empty javascript object:
1: getEnums = function() { 2: return $.Deferred(function(def) { 3: return em.fetchMetadata() 4: .then(function(data) { 5: utils.getOptionSets(data.schema.enumType, optionSets); 6: 7: def.resolve(); 8: 9: }).fail(function(error) { 10: def.reject(error); 11: }); 12: }).promise(); 13: }, This populates my empty optionSets object with an array of optionsets indexed to lists of "optionSetValue" classes. I can then bind to the optionset I need in a view using the "options" binding, where the enum server-side is called "LicenseType" in this case.
1: <div class="form-group"> 2: <label class="control-label">License Type</label> 3: <select data-bind="options: $root.optionSets['LicenseType'], optionsText:'name', optionsValue: 'name', value:LicenseType" class="form-control"></select> 4: 5: 6: 7: </div>
Net result:
