Ado Ado - 1 year ago 68
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 Source

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.


<script type="text/javascript">
    var xyz = <%=strJson%>;

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.


<script type="text/javascript">
    var xyz = @Html.Raw(ViewData["Json"]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download