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.


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)));