如何在Javascript中获取C#枚举

Jis*_*A P 26 javascript asp.net enumeration

我的C#代码中有一个枚举,我希望在javascript中获得相同的枚举.有没有办法在没有硬编码的情况下解决这个问题.

提前致谢

Sjo*_*erd 37

您可以将所有枚举值序列化为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>();
Run Code Online (Sandbox Code Playgroud)

这会注册一个脚本,如:

MyEnum={"Red":1,"Green":2,"Blue":3};
Run Code Online (Sandbox Code Playgroud)

  • 我意识到这是一个将近三年的答案,但是,我认为这是一个非常优雅的解决方案. (2认同)

Fre*_*son 5

如果你想要它作为 viewmodel -> view -> JS

要求:

using Newtonsoft.Json;
using System;
Run Code Online (Sandbox Code Playgroud)

视图模型:

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

然后在您的 .cshtml 中:

@* View *@

<script>
    var myEnumInJS = '@Html.Raw(Model.MyEumJson)';
</script>
Run Code Online (Sandbox Code Playgroud)

这将被评估为

在此处输入图片说明


Har*_*eem 5

是的,你可以这样做,我是这样做的:

    var OrderStateId = parseInt(stateVal);

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