c#服务器端枚举(enum)转为客户端javascript的枚举(json)

同时维护两边的enum估计有点烦(写起来也有点烦),写了个直接调来用,

不过,客户端写代码时引用枚举就不那么直观了……

 

public static string GetJsonEnum(Type enumType)
{
    
return GetJsonEnum(enumType, null);
}

public static string GetJsonEnum(Type enumType, string alias)
{
    
int[] values = (int[])Enum.GetValues(enumType);
    
string[] names = Enum.GetNames(enumType);
    
string[] pairs = new string[values.Length];

    
for (int i = 0; i < values.Length; i++)
    {
        pairs[i] 
= names[i] + ": " + values[i];
    }

    
if (string.IsNullOrEmpty(alias))
        alias 
= enumType.Name;

    
return string.Format("var {0}={{\n{1}\n}}", alias, string.Join(",\n", pairs));
}


aspx页面上调用方式:

<%=GetJsonEnum(typeof(LYL.Test.Domain.ProductTypeEnum))%>

 

页面执行时生成结果:

var ProductEnum={
TypeA
: 1,
TypeB
: 2,
TypeC
: 3
}

 

That's all.

 

 

posted @ 2008-11-07 11:25  果果’er  阅读(2003)  评论(0编辑  收藏  举报