asp net mvc C# list of objects to javascript array of objects Edit

Murugan Andezuthu Dharmaratnam | 17 September 2020 | 671

I have a list of countries with properties Id, Code, Name in my asp .net MVC C# backend code & wanted to have an array of the object of Country in the frontend .cshtml page. The solution is the serialize the list of countries into JSON and pass it to .cshtml page via model or viewbag and then convert it to array objects using jquery.

public class Country
{
    public int Id { get; set; }
    public int Code { get; set; }
    public String Name { get; set; }
}

You can serialize the list to JSON using Newtonsoft.Json.

List lstCountries = new Country().Get();
String countryJson = Newtonsoft.Json.JsonConvert.SerializeObject(lstCountries);

The above code will serialize the countries object and product JSON below.

[{"Id":1,"Code":91,"Name":"India"},{"Id":2,"Code":86,"Name":"China"},{"Id":3,"Code":1,"Name":"USA"},{"Id":4,"Code":91,"Name":"India"},{"Id":5,"Code":7,"Name":"Russia"},{"Id":6,"Code":91,"Name":"India"},{"Id":7,"Code":86,"Name":"China"}]

Now you need to pass the JSON to the view .cshtml file

ViewBag.Countries = countryJson; 

Final thing to do would be to convert the JSON to a javascript object.

var lstCountries = JSON.parse(@Html.Raw(Json.Encode(@ViewBag.Countries)));
console.log(lstCountries);