1

How to convert Asp.NET Enum to Json array, so it can be used for knockout options binding?

Options I see: is to create some custom enum extender (create method ConvertToJson that converts enum to Json) and write

<script>
    var myTypeEnum = @ConvertToJson(typeof(ClientTypeEnum)) ; 
</script>

and then I can use

 <select data-bind="options: myTypeEnum, ....></select>

But I believe there are better options, so I do need to write ConverToJson method by myself?

renathy
  • 5,125
  • 20
  • 85
  • 149
  • Do you need the values of the enum or the names? Or both? –  Nov 25 '13 at 12:23
  • Hmm.. I believe need both. I need to save updates values to DB (so probably Ids are necessary here) and show user names. – renathy Nov 25 '13 at 12:28

4 Answers4

1

I realise that this is using Web API rather than Razor in a view, but we've set up Json.Net to convert Enums to strings:

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Converters.Add(new StringEnumConverter());

With this set up, it just deals with serialising and deserialising enums to and from the string representation. It appears that you can set it up for Asp.Net.

Community
  • 1
  • 1
Paul Manzotti
  • 5,107
  • 21
  • 27
  • I need to have json array, I do not understand how this is related to arrays? – renathy Nov 26 '13 at 07:44
  • You would need to return an array with all the enum values in it, and the serialiser will turn them into the string representation for you, so you would get a list of the enum strings. Any other objects that have a property of that enum type will also have their value returned as the string representation, so you would map the selected enum value by a simple string comparison. – Paul Manzotti Nov 26 '13 at 08:53
  • What if I do not need enum values, but descriptions (defined using anotations)? – renathy Nov 26 '13 at 12:44
1
  1. Extending the HTMLHelper:
    public static MvcHtmlString EnumToJson(this System.Web.Mvc.HtmlHelper helper) where E : struct, IConvertible
    {
        var values = from E e in Enum.GetValues(typeof(E)) select String.Format(@"{{""Val"": {0:d}, ""Text"": ""{1}""}}", e, e.ToString());
        return MvcHtmlString.Create("[" + String.Join(",", values.ToArray()) + "]");
    }
  1. In javascript:
    var accessLevels = JSON.parse('@(Html.EnumToJson<MyEnum>())');
gbs
  • 3,529
  • 2
  • 20
  • 18
0

Not totally sure but you can try something like this:

// here is the string you pass to the client, a list separated by commas like Aaa, Bbb, Ccc
string result = Enum.GetNames(typeof(ClientTypeEnum)).Aggregate((s1, s2) => string.Format("{0},{1}", s1, s2)); 

// then a client sends a string to the server and you parse it like this
 ClientTypeEnum cte = (ClientTypeEnum) Enum.Parse(typeof(ClientTypeEnum), "EnumStr", true);
0

The previous answer about extending the Html helper works great, but the <T> was missing (or in that case <E>). It should be:

        
    public static MvcHtmlString EnumToJson<T>(this System.Web.Mvc.HtmlHelper helper) where T : struct, IConvertible
    {

        var values = from T e in Enum.GetValues(typeof(T)) select String.Format(@"{{""Value"": {0:d}, ""Text"": ""{1}""}}", e, e.ToString());
        return MvcHtmlString.Create("[" + String.Join(",", values.ToArray()) + "]");

    }

var accessLevels = JSON.parse('@(Html.EnumToJson())');

(I would have just added it as a comment to the original answer if I could, but my account needs to have 50 points to be able to comment o_O)

Henric Rosvall
  • 181
  • 1
  • 7