Ado Ado - 3 months ago 13
C# Question

Pass a C# custom array to JavaScript

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

Answer

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>
Comments