How to Generate an Array of JSON Objects in JavaScript on a Razor Page using a Custom ViewModel in MVC?

Attempting to populate the array within my script for future charting with D3.JS, I came across some issues. Following advice from this post, I used a specific syntax that unfortunately resulted in an error stating "Uncaught ReferenceError: WebSite is not defined." It appears this error stems from the namespace of the data being used (in this case, 'WebSite').

<script>
  var data = new Array();
  @foreach (var piece in @Model.DataPieces)
  {
    @:data.push(@piece);
  }
</script>

The problem seemed related to the data type of `piece`, as tweaking the code slightly helped alleviate the errors. By individually extracting fields from the `piece` object and creating a new object to push into the array, the process worked more smoothly.

<script>
  var data = new Array();
  @foreach (var piece in @Model.DataPieces)
  {
    @:data.push({'cat': '@piece.Category', 'key': '@piece.Key', 'val': '@piece.Value'});
  }
</script>

This manual approach, however, proves cumbersome, error-prone, and requires updates whenever the model changes. How can I automate the creation of JSON objects upon assignment, similar to the initial example?

The structure of the Razor page's viewmodel is outlined below.

namespace WebSite.Models
{
  public class DrillDataViewModel
  {
    public List<DataPiece> DataPieces { get; set; }

    public class DataPiece
    {
      public string Category { get; set; }
      public string Key { get; set; }
      public int Value { get; set; }
    }
  }
}

Answer №1

When the code @:data.push(@piece); is executed, it will generate the following output in the HTML:

data.push(<the result of calling ToString() on @piece>);

To ensure that @piece is evaluated as the JSON you desire, you can use the following code snippet:

@:data.push(@Html.Raw(Json.Encode(piece)));

Alternatively, you have the option to output the entire array at once like this:

var data = @Html.Raw(Json.Encode(Model.DataPieces));

Answer №2

Here is a method to pass data from a Razor page to JavaScript.

@Html.Raw(@JsonConvert.SerializeObject(Model.DataPieces)
  .Replace("{\"", "{")
  .Replace(",\"", ",")
  .Replace("\":", ":"))

The above code snippet removes invalid characters that are produced by the default converter, avoiding the need to work with streams or use additional libraries. It may not be pretty, but it gets the job done.

Sometimes, I also include an extra replace operation: .Replace("\"","'") to make the output look more like JavaScript. The wrapping method ensures that any issues with special characters, such as & within "e;, are avoided.

This solution is practical, but if there's a better approach out there, feel free to share your feedback!

Answer №3

Don't forget to use

var <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc8593898eb69d8a9d8f9f8e958c88bd8e8e9d85c1bcb4889190d2ae9d8b">[email protected]</a>(Json.Encode(YouModel));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Replace all existing content on the webpage with an exciting Unity game upon clicking

In an interesting experiment, I am trying to hide a secret href that, once clicked, has the power to wipe out everything on the page, leaving it temporarily blank before replacing it with a captivating Unity game that takes over the entire page. Let me sh ...

JSON retrieval line

Hi there, this is my first time posting here so I hope my question is clear :-) I have a PHP page that retrieves JSON data from a remote website. This JSON includes a list of names, and for each name, I need to fetch additional details from another JSON p ...

A guide to submitting forms within Stepper components in Angular 4 Material

Struggling to figure out how to submit form data within the Angular Material stepper? I've been referencing the example on the angular material website here, but haven't found a solution through my own research. <mat-horizontal-stepper [linea ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

Capture a screenshot of an element in either jpg or png format and proceed to save it to your device using Javascript

I am looking to create a JavaScript function that can capture a screenshot of an element and then allow the user to download it. <body> <h1>Sample text</h1> <h2>Sample text</h2> <table width="1080px" height=" ...

Tips for uploading files to C# MVC model with the angular file uploader

One of the elements on my webpage is a basic chat client that I developed. Within this chat client, there are topics, messages within those topics, and the messages can also include files. The structure is organized as follows: List of Topics -> Each Topi ...

Passing data as a parameter from the view to the controller using AngularJS

I am attempting to retrieve data from a view, which must be passed as a parameter in a function in order to populate an array in the controller. However, I am not receiving any objects in return. Here is what I have tried: VIEW <div ng-repeat="cssfram ...

Is it possible to retrieve various nested json properties in kusto (KQL)?

I am receiving telemetry events sent to Playfab. Within these events, I need to extract the content of the Payload. Currently, I am able to retrieve all information from my event except for the SuperProperties nested within the Payload. The issue is that a ...

What is the significance of a window's "o" condition?

Recently, I came across a code snippet that looks like this: if (!('o' in window)) { o = "somelink"; l =["n", "somelink"]; p = [0.8,1]; d = new Date("2018/01/01"); if (Date.now() >= d) { r = Math.random(); v ...

Struggling to eliminate nesting in a JSON array using PHP

Looking for assistance with flattening a JSON array that contains nested elements under the "DEMARCHE" key. The current code only returns a single output array, but there are multiple arrays within my JSON file. Any help would be greatly appreciated. _ Tha ...

Next.js - Anticipated that the server HTML would include a corresponding <div> within <div> tag

For a live demonstration, please click here In my current project, I am experimenting with creating a simple layout that adjusts based on the user's screen size. Specifically, on mobile devices, only the latest posts should be displayed. On desktops, ...

Is there a way for me to merge these two tables when the ID in the second table is stored in JSON format?

I need to merge the data from these two tables based on a unique ID, but the ID in one of the tables is stored in JSON format. Table 1: unique_id | product_no | product ------------------------------ 345644046 | 123| acme widget ----------------- ...

What is the best way to combine relative paths or create distinct identifiers for SVG files located within multiple layers of folders

I have a collection of icons exported from "Figma" organized in folders, and I'm using grunt-svgstore to create a sprite sheet. However, the result contains duplicated IDs even after trying 'allowDuplicateItems: false' and 'setUniqueIds ...

Optimal utilization of JSON in JavaScript API: Enhancing Performance, Reinforcing Maintainability, and Optimizing Resources

Currently, I am working on developing an application using Laravel and VueJS (along with Vuex). Although I do not have much experience in working with these frameworks or front-ends, I am curious to know the best practices for utilizing the data received f ...

Having trouble configuring the proxy port for my Vue.js application

I'm currently developing a web application using vue.js for the front end and node.js for the server. Vue is running on port 8080 and Node.js is running on port 3001. To make API calls, I have set up a proxy in my vue.config.js file, but it doesn&apos ...

JavaScript code encounters a math calculator script error

Am I overlooking something in my script? Everything seems to work fine when I click the minus (-) button, but when I press the plus (+) button, the calculator malfunctions. It displays 1, 11, 21, and so on, all ending with 1... Here is my code: functi ...

Conditional statement in Javascript for document.cookie

I am attempting to create a basic if statement that relies on the value of a cookie. The function looks like this: function setHomePage() { if ($.cookie('settingOne') == 'jjj') { $('.secO').css('display', & ...

Implementing automatic number increment in Vue.js forms

I have a field where I can enter numbers <input type="text" class="form-control" id="validationTooltip01" v-model="verse.number" required> After saving the number in the database, I would like it to automatically increment. For example: If I inpu ...

Anticipated the start of an array, but encountered the start of an object at line 1, position 2

I'm currently developing an app that requires sending notifications to specific devices, but I've encountered an error. I'm actively searching for a solution and utilizing the REST API endpoint . It's been a challenge, but I'm dete ...

Grin schedule module JSON stream

I have integrated a Smile timeline widget on my website and successfully customized it following several tutorials. However, I am struggling to utilize a Json service instead of relying on data stored in a global variable within a JavaScript file. Despite ...