I'm trying to retrieve an enum
from my C# code and implement it in javascript.
Is there a method to accomplish this without relying on hardcoded values?
I'm trying to retrieve an enum
from my C# code and implement it in javascript.
Is there a method to accomplish this without relying on hardcoded values?
To convert all enum values to JSON, you can use the following method:
private void SerializeEnumValues<T>()
{
var type = typeof(T);
var values = Enum.GetValues(type).Cast<T>();
var dictionary = values.ToDictionary(e => e.ToString(), e => Convert.ToInt32(e));
var jsonResult = new JavaScriptSerializer().Serialize(dictionary);
var scriptString = string.Format("{0}={1};", type.Name, jsonResult);
System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(), "ScriptKey", scriptString, true);
}
SerializeEnumValues<MyEnumType>();
This will generate a script output like:
MyEnumType={"Value1":1,"Value2":2,"Value3":3};
If you'd like to display it as viewmodel -> view -> JS
Prerequisites:
using Newtonsoft.Json;
using System;
Viewmodel:
// viewmodel property:
public string MyEumJson
{
get
{
return JsonConvert.SerializeObject(Enum.GetValues(typeof(MyEum)), new Newtonsoft.Json.Converters.StringEnumConverter());
}
}
Next, in your .cshtml file:
@* View *@
<script>
var myEnumInJS = '@Html.Raw(Model.MyEumJson)';
</script>
this will be interpreted as
Achieving this is possible, I managed to do it in the following way:
let stateId = parseInt(currentState);
if (stateId === @((int)States.Approved)) {
// State 5 is the Approved state
if (orderType === "Quote") {
$('#quoteSection').css('display', 'block');
}
If you want to convert it to a list and then serialize it to JSON, you can follow this example:
// Within the code-behind
private void _Default_Load(object sender, EventArgs e)
{
var objects = GetObjects();
var serializer = new JavaScriptSerializer();
this.MyHiddenField.Value = serializer.Serialize(objects);
}
// Example of an enumerable
static IEnumerable<MyClass> GetObjects()
{
for (int i = 0; i < 10; i++)
{
yield return new MyClass();
}
}
This method requires .Net 3.5 and a reference to the System.Web.Extensions
assembly in order to use JavaScriptSerializer
. However, there are alternative JSON serialization libraries available for .Net.
In your JavaScript code, make sure to utilize a JSON serialization library (like json2) to deserialize your list:
var mylist = JSON.parse($("#MyHiddenField").val());
for (var i in mylist)
{
var item = mylist[i];
}
Update: I apologize for not fully understanding the question - it should be about enumerating, not making something enumerable!
For Razor
Specifically designed for optimal use with Razor
var Enumerators = {
System: {
@{
<text>DayOfWeek: JSON.parse('@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Enum.GetValues(typeof(DayOfWeek)), new Newtonsoft.Json.Converters.StringEnumConverter()))')</text>
}
}
}
Enumerators.System.DayOfWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
If you notice any errors or if adjustments are needed to suit your requirements, please inform us. Thank You
For C# Server Side
Take a look at the provided answer which may be beneficial
Check out this helpful response related to your inquiry:
JSON serialization of C# enum as a string
After searching diligently, I stumbled upon an effective solution.
The only hiccup I encountered was the absence of the Description
attributes. While this flaw may not bother those who do not require descriptions, it might be a deal-breaker for some.
This nifty hack grants you client-side access as demonstrated below:
var Enums = {
phoneType: {phone:1,fax:2,voiceMail:3,cell:4,},
addressType: {mailing:1,physical:2,}
};
My recent project involved implementing a method to upload files in a share extension utilizing the wkwebview and a javascript bridge. This approach handles the upload process, where each part of the file is uploaded successfully before moving on to the ne ...
I have various sets of circles on a map - 10 red circles, 10 blue circles, and 10 green circles. Is there a way to use d3 selectAll or select to specifically choose only the red circles? Are there any alternative methods for achieving this? The color of ...
For a specific project, I developed a module that is responsible for splitting files based on the '\r\n' delimiter and then sending each line to an event listener in app.js. Below is a snippet of the code from this module. var fs = req ...
My current project involves implementing a post method on the server side to fetch all files within a specified directory (non-recursively). Below is my code snippet. I am encountering challenges in sending back the response (res.json(pathContent);) with ...
I am currently using jQuery to create a smooth fade-in effect for an <article> element that contains a <section> element. The outer element has CSS properties of display:none, position:fixed, and z-index:5. Meanwhile, the inner element is styl ...
I am faced with a perplexing puzzle that has left me scratching my head. Here are two seemingly identical pieces of javascript code, but one behaves unexpectedly (take note of the Console.Log): Updates the UI once, then abruptly stops updating: http://js ...
Hey there, I've been attempting to incorporate a delay() or setTimeOut function into this simple send message script, but I seem to be struggling with the syntax. Whenever I try to add these functions, I encounter numerous syntax errors. Even after fi ...
I am displaying a value in EJS and I am looking to format it to show fewer decimal places. This is related to the EJS engine on the frontend. Value displayed: 4.333333333333333 I want it to be displayed like this: 4.3 The EJS code snippet used: <p cl ...
Currently, I have a website that adapts its display based on whether the mobile device is in portrait or landscape orientation. The code I am using works on some devices, but on others, the orientation is flipped and the wrong page is displayed. Although t ...
My current project involves integrating a Google Docs solution into a web ASP.NET site for document management, specifically with Word and Excel files. I recently came across the Google Documents List Data API v2.0 on their developer guide page here. Here ...
I'm currently utilizing the Profile function of ASP.NET on a website, but encountering some strange behavior with updating profiles. It seems that users are unable to update their own profiles, whether they are regular web users or administrators. How ...
I am encountering an issue with my Angular 4 app and a .NET Web API on the same IIS server. The angular app is located in the "/wwwroot/angular/" folder, while the web API is in the "/wwwroot/api/" folder. When I make a request to the web API, it works fin ...
I'm struggling with understanding callbacks, especially how they function. Here is my function: function checkDuplicateIndex(values, callback) { $.ajax({ type: "POST", url: url, data: "command=checkIndexAlbumTracks& ...
I need to customize the ui-select-choices based on the selections from the ui-select Check out the Preview on Plunker View the source code on Plunker Within my UI Select, I have two options available: 1. Front 2. Back My goal is to change the color of ...
Struggling to load jquery, popperjs, and bootstrap (v4-beta) using requirejs, I'm consistently encountering this error in the console: Uncaught Error: Bootstrap dropdown require Popper.js (https://popper.js.org) at bootstrap.js:6 at bootstrap ...
When adjusting an RGB pixel map of a picture, which values would result in a more pronounced red, green, blue, cyan, magenta, or yellow appearance? In my current JavaScript code, I am using the following RGB change values to enhance colors, but I am curio ...
Cookie: $(document).ready(function(){ //hide all divs for the purpose of this example, you should have them hidden with your CSS //$('.picture.1').hide(); //check if the cookie is already set if ($.cookie("currentDiv") === ...
var newData = { a: ko.observable(), b: ko.observable(), c: ko.observable(), d: ko.observable() }; function setupControlEvents() { $("#save").on("click", handleSave); } function handleSave() { var dataToSen ...
Hey everyone! I need some help with a challenge I'm facing. I can't seem to get click coordinates to create a new Marker on my map. Check out the image here And another image here ...
While working with Angular JS to iterate through Twitter tweets using ng-repeat, I encountered the need to highlight certain parts of the tweet string such as @tag and #hash. To achieve this, it was suggested to utilize replace method to wrap these element ...