Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 javascript.

Is there any way to do this without hardcoding?

like image 701
Jishnu A P Avatar asked Mar 03 '11 07:03

Jishnu A P


People also ask

Is C hard to learn?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.

How long does it take to become C?

It can take anywhere from a few days to an entire lifetime. C is a fairly simple language to learn but a difficult one to master. The idea of “knowing C” is subjective and there is a large range in technical abilities depending on how deeply someone understands the language and its environment.

Should I learn C or C++ first?

There is no need to learn C before learning C++. They are different languages. It is a common misconception that C++ is in some way dependent on C and not a fully specified language on its own. Just because C++ shares a lot of the same syntax and a lot of the same semantics, does not mean you need to learn C first.


1 Answers

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}; 
like image 156
Sjoerd Avatar answered Sep 20 '22 09:09

Sjoerd