How do I convert a C# List to a Javascript array?

前端 未结 9 782
情书的邮戳
情书的邮戳 2020-11-27 16:56

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         


        
相关标签:
9条回答
  • 2020-11-27 17:41

    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>
    
    0 讨论(0)
  • 2020-11-27 17:41

    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>
    
    0 讨论(0)
  • 2020-11-27 17:48

    Here's how you accomplish that:

    //View.cshtml
    <script type="text/javascript">
        var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.Addresses))');
    </script>
    
    0 讨论(0)
提交回复
热议问题