Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdown filled with options provided by an enum (server side) with Breeze

I develop an asp.net mvc solution with durandal/breeze.

I have a dropdown where list is populated from an Enum provided by Entity Framework Code First. Here is the model server side:

public enum EnumCategory
{
    Cat1,
    Cat2,
    Cat3,
    Cat4
}

Here is the table which use this enum:

public class Transport
{
    [Key]
    public int Id { get; set; }
    public EnumCategory Category { get; set; }
    ...
}

My question: how to retrieve these values of the enum server side to be able to fill my dropdown client side? Do I have to create a new array manually client side like this:

 var categories = [
    { id: '' , description: '' },
    { id: 'Cat1', description: 'Category 1' },
    { id: 'Cat2', description: 'Category 2' },
    { id: 'Cat3', description: 'Category 3' },
    { id: 'Cat4', description: 'Category 4' }];

My view display this dropdown like this:

<select data-bind="options: $root.categories,
                   optionsText: 'description',
                   optionsValue: 'id',
                   value: category,
                   validationOptions: { errorElementClass: 'input-validation-error' },
                   valueUpdate: 'afterkeydown'">
 </select>

It seems redundant to me to have to recreate a list of values client side because we already have this list of values server side.

Any idea?

Thanks.

like image 541
Bronzato Avatar asked Mar 31 '13 17:03

Bronzato


2 Answers

You are right, it is redundant to have to repeat the enum definition on the client for an enum defined on the server. Ideally the breeze metadata should include the individual enum values that make up an Enum type.

Unfortunately, we haven't gotten there yet. But this is a very reasonable feature. Could you please add it to the Breeze User Voice. We take these suggestions very seriously in determining which features to work on next.

like image 52
Jay Traband Avatar answered Oct 01 '22 17:10

Jay Traband


As a workaround in the meantime, you could create global "enums" from your metadata like this:

manager.fetchMetadata()
    .then(function (data) {

        // extract all enums als global objects
        ko.utils.arrayForEach(data.schema.enumType, function (c) {
            window[c.name] = {};
            ko.utils.arrayForEach(c.member, function (m) {
                window[c.name][m.name] = m.value;
            });
        });

});

So if you had an enum called "Status", you would now have a global object that you can call:

var currentStatus = Status.Done; //returns the value as defined in the server side enum

These can then also be bound to dropdowns

like image 22
Dimitri Avatar answered Oct 01 '22 19:10

Dimitri