如何在 Javascript 中获取 C# 枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5177755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Get a C# Enumeration in Javascript
提问by Jishnu A P
I have a enum in my C# code and i want to get the same enum in javascript. Is there any way to fo this without hardcoding.
我的 C# 代码中有一个枚举,我想在 javascript 中获得相同的枚举。没有硬编码,有什么办法可以解决这个问题。
Thanks in advance
提前致谢
回答by Sjoerd
You can serialize all enum values to JSON:
您可以将所有枚举值序列化为 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};
回答by Fred Johnson
If you want it as viewmodel -> view -> JS
如果你想要它作为 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:
然后在您的 .cshtml 中:
@* View *@
<script>
var myEnumInJS = '@Html.Raw(Model.MyEumJson)';
</script>
this will be evaluated as
这将被评估为
回答by Harry .Naeem
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');
}
回答by Justin
You can convert it to a list and then serialise it to JSON, for example:
您可以将其转换为列表,然后将其序列化为 JSON,例如:
// 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.
以上需要 .Net 3.5 和对System.Web.Extensions
程序集的引用(为了使用JavaScriptSerializer
.Net,但是存在替代的 JSON 序列化库。
In your javascript code you should use a JSON serialisation library (such as json2) to deserialise your list:
在您的 javascript 代码中,您应该使用 JSON 序列化库(例如json2)来反序列化您的列表:
var mylist = JSON.parse($("#MyHiddenField").val());
for (var i in mylist)
{
var item = mylist[i];
}
Update:Agg, I promise to actually readthe question next time - enumeration, not enumerable!
更新:Agg,我保证下次会真正阅读这个问题 - enumeration,而不是enumerable!
回答by Zayar
回答by Ali Jamal
For Razor
剃须刀
Works perfectly for Razor like this
非常适合这样的 Razor
var Enumerators = {
System: {
@{
<text>DayOfWeek: JSON.parse('@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Enum.GetValues(typeof(DayOfWeek)), new Newtonsoft.Json.Converters.StringEnumConverter()))')</text>
}
}
}
这将在 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
对于 C# 服务器端
Please see the following answer that might be useful
请参阅以下可能有用的答案
回答by Aximili
I found a good solution here
我在这里找到了一个很好的解决方案
http://fairwaytech.com/2014/03/making-c-enums-available-within-javascript/
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.
我唯一的问题是它不带有Description
属性。如果您不使用/不需要描述,那么它是完美的。
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,}
};