Search code examples
c#typescriptrazorgeneric-collections

how to parse C# generic collection list in typescript


This is my .cshtml code,

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

And this is my typescript code to get the value above,

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

And this is the return value,

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

I just want to iterate through this collection. This is what I've tried

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

But it gives the output as System.Collections.Generic.List as string.
I want to iterate all the values inside this collection.

Edit

MyViewModel's properties are as follow,

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

Solution

  • You will need to serialize your collection and then output that serialized value as "Raw" (or else the razor engine will escape your JSON, and you don't want that)

    @using Newtonsoft.Json;
    
    @{
       var myList = JsonConvert.SerializeObject(ViewBag.MyColection);
    }
    
    <input id="myListHidden" type="hidden" data-my-list="@Html.Raw(myList)" />
    

    In this example, I use the Newtonsoft serializer. You can use it by installing the NuGet package.

    The above will generate something like this:

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

    You can then use the value how you wish

    EDIT:

    Note that if you do not use @Html.Raw() the razor engine will output this:

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