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

前端 未结 9 874
情书的邮戳
情书的邮戳 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条回答
  •  -上瘾入骨i
    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
    Addresses = new List
    (); 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"}]
    

提交回复
热议问题