44

我有一个数据表,我将其转换为列表,对其进行序列化并使用视图模型将其传递给我的视图。

我的视图模型如下所示:

public class AddressModel
{
    public string Addresses { get; set; }
}

我的控制器操作如下所示:

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);

然后在我看来,我得到以下地址字符串:

[["123 Street St.","City","CA","12345"],["456 Street St.","City","UT","12345"],["789 Street St.","City","OR","12345"]]

我应该如何将驻留在剃刀模型中的序列化字符串转换为 javascript 数组?

4

9 回答 9

56

您可以直接将值注入 JavaScript:

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

JSON.parseHtml.Raw

或者,您可以通过 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

于 2013-08-27T16:28:23.620 回答
35

Json Parse 的许多方法,但我找到了最有效的方法

 @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>
于 2016-02-26T12:05:18.977 回答
19

这在 ASP.NET Core MVC 中对我有用。

<script type="text/javascript">
    var ar = @Html.Raw(Json.Serialize(Model.Addresses));
</script>
于 2018-01-24T15:10:35.130 回答
15

其中许多答案确实有效,但我发现迄今为止最简单的方法是通过 ViewData 或 ViewBag 发送数据并让 JSON.Net 对其进行序列化。

当页面加载之前需要 Javascript 生成 HTML 或需要避免 AJAX 开销时,我会使用此技术:

在控制器中:

public ActionResult MyController()
{
    var addresses = myAddressesGetter();
    ViewData["addresses"] = addresses ;
    return View();
}

在视图中:

@section scripts {
<script type="text/javascript">
    var MyjavascriptAddresses: @Html.Raw(JsonConvert.SerializeObject(ViewData["addresses"])),
</script>
}

您始终可以依赖 JSON.NET,而某些浏览器对 JSON 反序列化的支持很差。与某些方法相比的另一个好处是您可以使用浏览器的 Javascript 查看 Javascript View --> Source,因为它只是在服务器端生成的文本。

请注意,在大多数情况下,Web API 是一种将 JSON 发送到客户端的更优雅的方式。

于 2014-12-09T00:57:21.463 回答
4

我想说这更多的是您对数据建模的方式的问题。与其使用字符串数组作为地址,不如这样更简洁、更容易:

创建一个类来表示您的地址,如下所示:

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

然后在您的视图模型中,您可以像这样填充这些地址:

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);
    }
}

这将为您提供如下所示的 JSON:

[{"Address1" : "123 Easy Street", "CityName": "New York", "StateCode": "NY", "ZipCode": "12345"}]
于 2013-08-27T16:38:29.660 回答
4

对于那些尝试不使用 JSON 的人来说,以下是我的做法:

<script>
    var originalLabels = [ '@Html.Raw(string.Join("', '", Model.labels))'];
</script>
于 2017-07-28T15:19:25.623 回答
1

对于一维数组

控制器:

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 

看法:

<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>
于 2019-04-30T18:40:25.690 回答
1

以下是你如何做到这一点:

//View.cshtml
<script type="text/javascript">
    var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.Addresses))');
</script>
于 2018-04-30T16:11:24.277 回答
0

JSON 无论如何都是有效的 JavaScript 对象,当您打印 JavaScript 本身时,一旦将 JSON 转换为 JSON,您就不需要进一步编码/解码 JSON。

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

将打印以下内容,它是有效的 JavaScript 表达式。

<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>
于 2013-08-27T17:45:16.350 回答