0

I have the following C# array and I would like to pass it to JavaScript. What would be the best way to achieve it? Thank you?

public static List<ListDetail> GetMyList()
{
    List<ListDetail> myList = new List<ListDetail>();
    myList.Add(new ListDetail() { Id = 1, Name = "Party" });
    myList.Add(new ListDetail() { Id = 2, Name = "Course" });
    myList.Add(new ListDetail() { Id = 3, Name = "Home" });
    return myList.ToArray;
}
Ado
  • 65
  • 9

1 Answers1

2

You can use JsonConvert to convert your objects into a JSON string, so they can be easily manipulated by JavaScript

// declare variable on your class
public string strJson; 
...  
// assign value in relevant method
strJson = Newtonsoft.Json.JsonConvert.SerializeObject(new myList);

All you need to do then is expose the string in your front-end website.

If you're using webforms, you could use <%=strJson %> inside a <script> tag. Alternatively, you could use a Literal.

Example:

<script type="text/javascript">
    var xyz = <%=strJson%>;
    console.log(xyz);
</script>

Or, if you're using MVC, you could use ViewData["Json"] = strJson; in your controller, and then @Html.Raw(ViewData["Json"]) inside a <script> tag in your View.

Example:

<script type="text/javascript">
    var xyz = @Html.Raw(ViewData["Json"]);
    console.log(xyz);
</script>
Andy-Delosdos
  • 3,560
  • 1
  • 12
  • 25
  • Thank you for the reply. And then how can I convert fro JavaScript the JSON to an array? – Ado Aug 21 '16 at 10:50
  • You can use `Newtonsoft.Json.Linq.JArray.Parse(strJson)` if its an array, or `Newtonsoft.Json.Linq.JObject.Parse(strJson)` if its an object. Or you can use `Newtonsoft.Json.JsonConvert.DeserializeObject()` to deserialize the string to a specific .NET class. – Andy-Delosdos Aug 21 '16 at 10:53