How do I convert a C# List<string[]> to a Javascript array?
I have a datatable that I'm converting into a List, serializing it and passing it to my view using a viewmodel.
My viewmodel looks like this:
public class AddressModel
{
public string Addresses { get; set; }
}
My controller action looks like the following:
AddressModel lAddressGeocodeModel = new AddressGeocodeModel();
List<string[]> lAddresses = new List<string[]>();
string lSQL = " select Address1, CityName, StateCode, ZipCode " +
" from AddressTable ";
// Convert the data to a List to be serialized into a Javascript array.
//{
...data retrieval code goes here...
//}
foreach (DataRow row in AddressTable.Rows)
{
string[] lAddress = new string[5];
lAddress[1] = row["Address1"].ToString();
lAddress[2] = row["CityName"].ToString();
lAddress[3] = row["StateCode"].ToString();
lAddress[4] = row["ZipCode"].ToString();
lAddresses.Add(lAddress);
}
lAddressGeocodeModel.UnitCount = lAddresses.Count().ToString();
// Here I'm using the Newtonsoft JSON library to serialize my List
lAddressGeocodeModel.Addresses = JsonConvert.SerializeObject(lAddresses);
return View(lAddressModel);
Then in my view I get the following string of addresses:
[["123 Street St.","City","CA","12345"],["456 Street St.","City","UT","12345"],["789 Street St.","City","OR","12345"]]
How am I supposed to get this serialized string residing in a razor model into 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>