开发者

How to get Get a C# Enumeration in Javascript

I have an enum in my C# code and I want to get the same enum in java开发者_StackOverflow中文版script.

Is there any way to do this without hardcoding?


You can serialize all enum values to JSON:

private void ExportEnum<T>()
{
    var type = typeof(T);
    var values = Enum.GetValues(type).Cast<T>();
    var dict = values.ToDictionary(e => e.ToString(), e => Convert.ToInt32(e));
    var json = new JavaScriptSerializer().Serialize(dict);
    var script = string.Format("{0}={1};", type.Name, json);
    System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "CloseLightbox", script, true);
}

ExportEnum<MyEnum>();

This registers a script like:

MyEnum={"Red":1,"Green":2,"Blue":3};


If you want it as viewmodel -> view -> JS

Requires:

using Newtonsoft.Json;
using System;

Viewmodel:

// viewmodel property:
 public string MyEumJson
        {
            get
            {
                return JsonConvert.SerializeObject(Enum.GetValues(typeof(MyEum)), new Newtonsoft.Json.Converters.StringEnumConverter());
            }
        }

Then in your .cshtml:

@* View *@

<script>
    var myEnumInJS = '@Html.Raw(Model.MyEumJson)';
</script>

this will be evaluated as

How to get Get a C# Enumeration in Javascript


Yes you can do it like this, i did it like this:

    var OrderStateId = parseInt(stateVal);

    if (OrderStateId === @((int)OrderStates.Approved)) {
        // 5 is the Approved state
        if (OrderOption === "Quote") {
        $('#quoteDiv').css('display', 'block');
    } 


You can convert it to a list and then serialise it to JSON, for example:

// In the code-behind
private void _Default_Load(object sender, EventArgs e)
{
    var objects = GetObjects();

    var serialiser = new JavaScriptSerializer();
    this.MyHiddenField.Value = serialiser.Serialize(objects);
}

// Example enumerable
static IEnumerable<MyClass> GetObjects()
{
    for (int i = 0; i < 10; i++)
    {
        yield return new MyClass();
    }
}

The above requires .Net 3.5 and a reference to the System.Web.Extensions assembly (for the use of JavaScriptSerializer, however alternative JSON serialisation libraries exist for .Net.

In your javascript code you should use a JSON serialisation library (such as json2) to deserialise your list:

var mylist = JSON.parse($("#MyHiddenField").val());
for (var i in mylist)
{
     var item = mylist[i];
}

Update: Agg, I promise to actually read the question next time - enumeration, not enumerable!


For Razor

Works perfectly for Razor like this

var Enumerators = {
   System: {
           @{
               <text>DayOfWeek: JSON.parse('@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Enum.GetValues(typeof(DayOfWeek)), new Newtonsoft.Json.Converters.StringEnumConverter()))')</text>
           }
    }
}

This would give result like this in javaScript
Enumerators.System.DayOfWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]

Please let me know if there is a mistake or not accordingly fitting to the required need, Thank You

For C# Server Side

Please see the following answer that might be useful

https://stackoverflow.com/a/29184357/6737444


Here is the post that answered your question:

JSON serialization of enum as string


I found a good solution here

http://fairwaytech.com/2014/03/making-c-enums-available-within-javascript/

The only problem I have is that it doesn't carry the Description attributes. If you don't use/need descriptions then it is perfect.

This provides you with access on the client side, like so:

var Enums = { 
    phoneType: {phone:1,fax:2,voiceMail:3,cell:4,},
    addressType: {mailing:1,physical:2,} 
    };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜