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>();
这会注册一个脚本,如:
MyEnum={"Red":1,"Green":2,"Blue":3};
如果你想要它作为 viewmodel -> view -> JS
要求:
using Newtonsoft.Json;
using System;
视图模型:
// viewmodel property:
 public string MyEumJson
        {
            get
            {
                return JsonConvert.SerializeObject(Enum.GetValues(typeof(MyEum)), new Newtonsoft.Json.Converters.StringEnumConverter());
            }
        }
然后在您的 .cshtml 中:
@* View *@
<script>
    var myEnumInJS = '@Html.Raw(Model.MyEumJson)';
</script>
这将被评估为
是的,你可以这样做,我是这样做的:
    var OrderStateId = parseInt(stateVal);
    if (OrderStateId === @((int)OrderStates.Approved)) {
        // 5 is the Approved state
        if (OrderOption === "Quote") {
        $('#quoteDiv').css('display', 'block');
    } 
| 归档时间: | 
 | 
| 查看次数: | 25226 次 | 
| 最近记录: |