如何转换一个C#列出<字符串[]>一个JavaScript数组? [英] How do I convert a C# List<string[]> to a Javascript array?

查看:161
本文介绍了如何转换一个C#列出<字符串[]>一个JavaScript数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我转换成一个列表,序列化,并使用视图模型将它传递给我的看法的DataTable。

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"]]

我怎么让居住在剃刀模型转换为JavaScript数组这种序列化的字符串?

How am I supposed to get this serialized string residing in a razor model into a javascript array?

推荐答案

您可以直接注入值转换为JavaScript:

You could directly inject the values into JavaScript:

//View.cshtml
<script type="text/javascript">
    var arrayOfArrays = JSON.parse('@Html.Raw(Model.Addresses)');
</script>

请参阅<$c$c>JSON.parse, Html.Raw

另外,您可以通过Ajax获得的值:

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>

请参阅 jQuery.ajax

这篇关于如何转换一个C#列出&LT;字符串[]&GT;一个JavaScript数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆