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

前端 未结 9 781
情书的邮戳
情书的邮戳 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:24

    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

    0 讨论(0)
  • 2020-11-27 17:30

    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.

    0 讨论(0)
  • 2020-11-27 17:32

    I would say it's more a problem of the way you're modeling your data. Instead of using string arrays for addresses, it would be much cleaner and easier to do something like this:

    Create a class to represent your addresses, like this:

    public class Address
    {
        public string Address1 { get; set; }
        public string CityName { get; set; }
        public string StateCode { get; set; }
        public string ZipCode { get; set; }
    }
    

    Then in your view model, you can populate those addresses like this:

    public class ViewModel
    {
        public IList<Address> Addresses = new List<Address>();
    
        public void PopulateAddresses()
        {
            foreach(DataRow row in AddressTable.Rows)
            {
                Address address = new Address
                    {
                        Address1 = row["Address1"].ToString(),
                        CityName = row["CityName"].ToString(),
                        StateCode = row["StateCode"].ToString(),
                        ZipCode = row["ZipCode"].ToString()
                    };
                Addresses.Add(address);
            }
    
            lAddressGeocodeModel.Addresses = JsonConvert.SerializeObject(Addresses);
        }
    }
    

    Which will give you JSON that looks like this:

    [{"Address1" : "123 Easy Street", "CityName": "New York", "StateCode": "NY", "ZipCode": "12345"}]
    
    0 讨论(0)
  • 2020-11-27 17:35

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

    JSON is valid JavaScript Object anyway, while you are printing JavaScript itself, you don't need to encode/decode JSON further once it is converted to JSON.

    <script type="text/javascript">
        var addresses = @Html.Raw(Model.Addresses);
    </script>
    

    Following will be printed, and it is valid JavaScript Expression.

    <script type="text/javascript">
        var addresses = [["123 Street St.","City","CA","12345"],["456 Street St.","City","UT","12345"],["789 Street St.","City","OR","12345"]];
    </script>
    
    0 讨论(0)
  • 2020-11-27 17:39

    This worked for me in ASP.NET Core MVC.

    <script type="text/javascript">
        var ar = @Html.Raw(Json.Serialize(Model.Addresses));
    </script>
    
    0 讨论(0)
提交回复
热议问题