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
For those trying to do it without using JSON, the following is how I did it:
<script>
var originalLabels = [ '@Html.Raw(string.Join("', '", Model.labels))'];
</script>
For one dimension array
Controller:
using Newtonsoft.Json;
var listOfIds = _dbContext.Countries.Where(x => x.Id == Country.USA).First().Cities.Where(x => x.IsCoveredByCompany).Select(x => x.Id).ToList();
string strArrayForJS = JsonConvert.SerializeObject(listOfIds); // [1,2,6,7,8,18,25,61,129]
//Now pass it to the view through the model or ViewBag
View:
<script>
$(function () {
var myArray = @HTML.Raw(Model.strArrayForJS);
console.log(myArray); // [1, 2, 6, 7, 8, 18, 25, 61, 129]
console.log(typeof (myArray)); //object
});
</script>
Here's how you accomplish that:
//View.cshtml
<script type="text/javascript">
var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.Addresses))');
</script>