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?
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?
You can convert it to a list and then serialise it to JSON, for example:
The above requires .Net 3.5 and a reference to the
System.Web.Extensions
assembly (for the use ofJavaScriptSerializer
, however alternative JSON serialisation libraries exist for .Net.In your javascript code you should use a JSON serialisation library (such as json2) to deserialise your list:
Update: Agg, I promise to actually read the question next time – enumeration, not enumerable!
Here is the post that answered your question:
JSON serialization of enum as string
You can serialize all enum values to JSON:
This registers a script like:
I found a good solution here
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.This provides you with access on the client side, like so:
If you want it as viewmodel -> view -> JS
Requires:
Viewmodel:
Then in your .cshtml:
this will be evaluated as
Yes you can do it like this, i did it like this:
For Razor
Works perfectly for Razor like this
This would give result like this in javaScript
Please let me know if there is a mistake or not accordingly fitting to the required need, Thank You
For C# Server Side
Please see the following answer that might be useful
https://stackoverflow.com/a/29184357/6737444