Transforming a nested list in asp.net mvc c# into a JavaScript array

These are the models I am working with:

public class ModelA
{
  List<ModelB> ModelB {get;set;}
}

public class ModelB
{
  List<ModelC> ModelC {get;set}
}

In an attempt to convert these models into my view, I referred to this answer.

<script>
        var modelB = '@Html.Raw(Json.Encode(Model.ModelB))';
        var modelBData = JSON.parse(modelB);

        // However, I encountered an issue when trying to convert ModelC into a javascript array.
        var modelC = '@Html.Raw(Json.Encode(Model.ModelB.ModelC))';

</script>

I was able to convert Model B into a JavaScript array successfully, but struggled with converting Model C. Can someone please help me figure out how to convert the list of ModelC within ModelB into a JavaScript array? Any assistance in identifying where I may be making a mistake would be greatly appreciated.

Answer №1

let data = '@Html.Raw(Json.Encode(Model.ModelB.ModelC))';

Update to:

let data = '@Html.Raw(Json.Encode(Model.ModelB.SelectMany(z => z.ModelC)))';

Utilizing the SelectMany method will allow for serialization of all instances of ModelC within any of the ModelB objects.

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

Add the term "Pick" into the dropdown using Linq

After loading the drop down box from LINQ, everything is functioning properly. CustomerDataContext customer = new CustomerDataContext(); ddlCust.DataSource = from cust in customerDC.Customers orderby cust.CustId ascendi ...

Make Angular able to open a new window using window.open instead of opening a popup

Can anyone help me figure out how to use window.open to open a PDF file in a new tab for user download? Below is the Angular 4 code I'm currently using: download() { const data = {html: this.template.toArray()[0].nativeElement.innerHTML}; th ...

Leveraging Next Js with an external REST API for streamlined authentication and authorization functionality

I am currently working on transitioning my existing application that was developed with Node.js and Express, along with a front end built using create-react-app with Redux, to Next.js. However, I have hit a roadblock as I am unsure of the correct method ...

Unable to establish an external connection with the node

Currently, I am in the process of establishing a connection to a local server and running an app on port 8080 using node. Both node and apache are installed on my system. When Apache is active, I can access the server externally. However, when Node is runn ...

Is there a way to determine if my array includes a word with spaces?

int count; count = scanner.nextInt(); String words[] = new String[count]; for (int i = 0; i < count; i++) { words[i] = scanner.next(); if (words[i].equals("hey guys")) System.out.println("hey guys"); else System.out.println(" ...

Looking to align the labels of material UI tabs to the left instead of their default center alignment? Here's how

Is there a way to align material ui tab labels to the left instead of center by default? View an image demonstrating center aligned tab labels here ...

Creating a table of objects in Java by extracting data from a file: A step-by-step guide

Hello, I am interested in learning how to create a table of objects in Java using data from a text file. I have initialized my table as follows: Table tab[] = new Table[6] Below is the content of my text file: id|des|pr 50 | Internet Fibre 50 ...

Unlocking the power of JSONB column filtering in KNEX with Typescript/Javascript: A comprehensive guide

Could someone please assist me with this query issue? I have a table with a jsonb column that stores stringified data in the following format: entry: { 1: "data1", 2: "data2" } I am trying to retrieve entries where the key is 1 ...

What is the best way to handle resolving a promise nested within another promise and retrieving the result within a controller?

I have a situation where I need to modify the result of a promise returned by a function in one service and make this altered value accessible to my controllers from another service. angular.module('test').service("service1", function($q) { ...

Text appearing upon access to the website displaying robots.txt content

There seems to be an issue with our web server (IIS) where it displays the content of robots.txt instead of the actual site. Do you have any insights on what might be causing this and how we can resolve it? Screenshot of the problem here ...

Utilize PHP Sub-Arrays with Key References

Currently, I am experimenting with PHP 5.4 to handle data received from an HTTP API in XML format. To convert this XML data into an array, I utilize the following process: $xml = simplexml_load_string($resp); $json = json_encode($xml); $arr = json_decode( ...

Having trouble displaying a JSON response on an HTML page with AJAX

I've written an AJAX function that goes like this: function ajx(){ var ajaxRequest; // This variable makes Ajax possible! try{ // Works in Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // For Internet Exp ...

Easily changing the state of a specific array item using React

I'm having trouble updating the state of a specific item in an array called reviews. Can someone guide me on how to achieve this? The following code snippet is not working as expected: this.setState({ reviews[2].current: true }); Below is the comp ...

User missing in the transition from POST to GET

My journey with Node has just begun, and I decided to delve into the Rocket Rides demo available on GitHub. While exploring the pilot sign-up feature on the web app, I encountered a roadblock when trying to implement a similar functionality for passenger s ...

Tips on sorting through an array of subdocuments using two criteria in each subdocument

I am currently working on implementing a help request system that restricts the requester to submitting only one help request per topic to an expert. If the expert has multiple topics they can provide help with, I want to limit each requester to one help r ...

Node.js not receiving data event in CORS ajax call

I am currently encountering an issue where the data event in my jQuery process is not being called when trying to receive JSON from an AJAX CORS call. Despite printing the JSON on the screen and verifying its presence, the data event remains uninvoked. Aft ...

What is the best way to release allocated memory when it is no longer needed within the same scope in which it was initially assigned by the generating function?

I've highlighted the issue with comments in the code snippet below: class MyCustomClass //A class that manages a dynamic char array. { public: MyCustomClass(unsigned int size) { data = new char[size]; } char* GetModifiedCharArray() //I use this meth ...

PHP/MySQL clarification regarding time slots

Could someone assist me with this discussion I found? Due to my low reputation, I am unable to comment for further clarification. Although I grasp the solution provided in the mentioned discussion, I am struggling to comprehend how to pass the data to my ...

"Exploring the mechanics of this code: delving into the Buffer()

On a particular website, there is a task where you can solve puzzles and then compare your solution with others. I came across one solution that seems very concise and I'm having trouble understanding it. The task involves determining whether two cel ...

I have noticed that when I assign a pointer to an array, I often encounter a situation where the memory address of the pointer itself is distinct from the memory address of the first element in the

#include <stdio.h> int main() { int array[5]; array[0] = 10; array[1] = 20; array[2] = 30; array[3] = 40; array[4] = 50; int *pointer = &array; printf("Address of first element in the array: %p\n", &array[0]); printf("M ...