How do I convert a C# List<string[]> to a Javascript array?
You could directly inject the values into JavaScript:
//View.cshtml
<script type="text/javascript">
var arrayOfArrays = JSON.parse('@Html.Raw(Model.Addresses)');
</script>
See JSON.parse
, Html.Raw
Alternatively you can get the values via Ajax:
public ActionResult GetValues()
{
// logic
// Edit you don't need to serialize it just return the object
return Json(new { Addresses: lAddressGeocodeModel });
}
<script type="text/javascript">
$(function() {
$.ajax({
type: 'POST',
url: '@Url.Action("GetValues")',
success: function(result) {
// do something with result
}
});
});
</script>
See jQuery.ajax
Many way to Json Parse but i have found most effective way to
@model List<string[]>
<script>
function DataParse() {
var model = '@Html.Raw(Json.Encode(Model))';
var data = JSON.parse(model);
for (i = 0; i < data.length; i++) {
......
}
</script>
Many of these answers do work, but I have found the easiest way by far is to send data through ViewData or ViewBag and let JSON.Net serialize it.
I use this technique when Javascript is needed for HTML generation before the page load or when AJAX overhead needs to be avoided:
In the controller:
public ActionResult MyController()
{
var addresses = myAddressesGetter();
ViewData["addresses"] = addresses ;
return View();
}
In the view:
@section scripts {
<script type="text/javascript">
var MyjavascriptAddresses: @Html.Raw(JsonConvert.SerializeObject(ViewData["addresses"])),
</script>
}
You can always rely on JSON.NET whereas some browsers have poor JSON deserialization support.
Another benefit over some methods in that you can see the Javascript using your browser's View --> Source
, since it is simply text generated server-side.
Note that In most situations, Web API a more elegant way to get JSON to the client.