tips for extracting data from C# generic collection lists using TypeScript

This is the code I wrote in my .cshtml file:

  @ { var myList = (List<MyViewModel>)ViewBag.MyCollection; }
    <input id="myListHidden" type="hidden" data-my-list="@myList" />

Next, here is the TypeScript code that retrieves the value from above:

     let _myList = $('#myListHidden').data('my-list');  

The return value is:

      "System.Collections.Generic.List`1[MyProject.Data.ViewModels.MyViewModel]"

I am attempting to iterate through this collection by using the following code:

     for (let entry of _myList ) {
         console.log(entry);
       }

However, it only outputs System.Collections.Generic.List as a string. I need to access and iterate through all the values inside the collection.

Edit:

The properties of MyViewModel are as follows:

    public long Id { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }

Answer №1

Serialize your collection and output the serialized value as "Raw" to prevent JSON from being escaped by the razor engine.

@using Newtonsoft.Json;

@{
   var myList = JsonConvert.SerializeObject(ViewBag.MyColection);
}

<input id="myListHidden" type="hidden" data-my-list="@Html.Raw(myList)" />

In this instance, I utilized the Newtonsoft serializer, which can be easily installed through NuGet.

The output will resemble something along these lines:

<input id="myListHidden" type="text" data-my-list="[{"Id":1,"Name":"Bob","Active":true}]" />

You are free to use the value in any way you prefer.

UPDATE:

Remember that failing to utilize @Html.Raw() will yield the following result from the razor engine:

<input id="myListHidden" type="text" data-my-list="[{&quot;Id&quot;:1,&quot;Name&quot;:&quot;Bob&quot;,&quot;Active&quot;:true}]" />

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

What is the best way to find the point where two lines intersect using GDI+?

Currently, I am utilizing .NET to develop a drawing surface application that is akin to Visio. The user interface links two objects together on the screen using Graphics.DrawLine. While this basic approach functions adequately, it becomes apparent that as ...

Exporting Types in an NPM Package: Best Practices

Struggling to create a private NPM package for internal use within my company's Nodejs applications using Typescript. Currently, I have a basic proof of concept with some constants, but I'm having trouble structuring it in a way that is importabl ...

Using TypeScript to pass a callback function to labelFormatter in the legend of a Highcharts chart

I am currently experimenting with integrating HighCharts into an Angular2 project using TypeScript. My goal is to customize the appearance of the legend text, adding an image next to it. I've found that HighCharts provides a labelFormatter property w ...

Unable to display data retrieved from JSON file

I am encountering an unusual issue while trying to retrieve elements from JSON in JavaScript. I fetch a JSON string from a URL using the following code: // Create Request HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"www.someurl ...

Using setTimeout() and clearTimeout() alongside Promises in TypeScript with strict mode and all annotations included

Many examples of timer implementations using Promises in JavaScript seem overly complex to me. I believe a simpler approach could be taken. However, I am looking for a solution specifically tailored for TypeScript with the "strict": true setting and all ne ...

What is the best way to list the choices associated with a specific category?

The Node.js package I'm currently working with requires an argument of a specific type, which I can see is defined through a TypeScript declaration as follows: export declare type ArgType = 'A' | 'B' | 'C'; I am interes ...

I encountered an error with Firebase when attempting to run functions on my local machine

Encountering a Firebase error when running the function locally using emulator in CLI $ firebase emulators:start --only functions Initiating emulators: ["functions"] functions: Using node@8 from host. functions: Emulator started at http://localhost:50 ...

Next.js Custom App now offers full support for Typescript in Accelerated Mobile Pages (

I am looking to implement AMP in my custom Next.js project using Typescript. While the official Next.js documentation does not offer support for Typescript, it suggests creating a file called amp.d.ts as a workaround. My application includes a src folder ...

How can I change a Task into a List in this scenario?

Help needed with this issue... Encountering an error message: Unable to convert type 'System.Threading.Tasks.Task System.Collections.Generic.List Thoughts.ViewModel.PickerViewModel.Location'** to **'System.Collections.Generic.List Thought ...

Determining When to Activate Button Based on Angular - Verifying That All Choices Have Been Ch

This quiz application requires the user to choose options before proceeding to the next page, with the next button being disabled by default. Once all options are chosen, the next button should become enabled. NOTE: Although the functionality for selecti ...

I'm experiencing difficulty in scrolling on my Nextjs web application

Currently, I am facing an issue with my portfolio webpage which is divided into 3 main components - Hero, About, and Portfolio. The layout structure is as follows: export default function RootLayout({ children, }: { children: React.ReactNode }) { ret ...

Utilizing a JSON object to send data to a C# WebAPI POST endpoint that accepts a parameter of a generic abstract class

I have a generic abstract class that defines the structure of an object to be POSTed to this endpoint. The class is as follows, with an example implementation: public abstract class Animal<T> { public string Name { get; set; } pu ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

Creating an external link in Angular with query parameters

I have created an app where users have their addresses listed, and I want to implement a feature that allows me to open Google Maps when clicking on the address. However, I am currently facing an issue where instead of getting the actual value of {{ this. ...

What causes type checks to be skipped when spreads are used on type-guarded types?

Query: Why doesn't a compile-time error occur when I overlook adding nested fields to an object of type T, while constructing the object using object spread? Illustration: interface User { userId: number; profile: { username: string } } f ...

Enhanced File Upload Experience with MVC Pop-up Feature

I need to import some XML files into my MVC application. To do this, I want to create a popup window that allows me to upload the file. Below is the code I have written. In the controller, I can see the uploaded file. Upload.cshtml: @using (@Html.BeginFo ...

Add a string with a special character ' to the SQL database

I need to add a string to a SQL table that may include a single quotation character. What is the best approach to achieve this? Should I use a backslash before the single quotation? Here is the command within a C# code: SqlCommand myCommand = new SqlComma ...

Creating a webcrawler in C# to download a website featuring ajax pages

Recently, I completed a straightforward web crawler project in C# using Microsoft WebCrawler. This project is designed to download the content from a specific website. In order to ensure successful page retrieval, I have set up an event listener for Docum ...

Having trouble appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...