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

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the reply. And then how can I convert fro JavaScript the JSON to an array?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.