如何将C#List <string []>转换为Javascript数组?</string []>

时间:2013-08-27 16:16:47

标签: c# javascript razor

我有一个数据表,我正在转换为List,序列化它并使用viewmodel将其传递给我的视图。

我的viewmodel看起来像这样:

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

我应该如何将这个序列化的字符串存放在razor模型中的javascript数组中?

9 个答案:

答案 0 :(得分:44)

您可以直接将值注入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

答案 1 :(得分:21)

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

Option Explicit

Sub SearchAndDeleteList2()

Dim dataSht As Worksheet
Dim dataRng As Range, namesRng As Range, cell As Range, rangeToDelete As Range
Dim firstAddress As String


'------------------------------
' setting stuff - begin
Set dataSht = ThisWorkbook.Sheets("Sheet1Data") '<== change 'data' sheet as per your needs
With dataSht
    Set dataRng = .Range("A11:A" & .Cells(.Rows.Count, 1).End(xlUp).row)
End With
If dataRng.Rows(1).row < 11 Then Exit Sub

With ThisWorkbook.Sheets("Sheet2Names") '<== change 'names' sheet as per your needs
    Set namesRng = .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).row)
End With

Call ApplicationSet(False, False, xlCalculationManual, False)
' setting stuff - end
'------------------------------


'------------------------------
' core code - begin
Set cell = dataRng.Find("End:", LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext)
If Not cell Is Nothing Then
    firstAddress = cell.Address
    Do
        If Not MyMatch(GetName(cell.Offset(-2)), namesRng) Then Call UpdateRngToDelete(rangeToDelete, dataSht.Rows(cell.row).Offset(-3).Resize(4))

        Set cell = dataRng.FindNext(cell)
    Loop While cell.Address <> firstAddress

    rangeToDelete.Delete
End If
' core code - end
'------------------------------


Call ApplicationSet(True, True, xlCalculationAutomatic, True)

End Sub


Function GetName(cell As Range) As String
Dim iIni As Integer
Dim iEnd As Integer

iIni = InStr(cell.value, """") '<== the 'name' is always preceeded by '"' character
iEnd = InStr(cell.value, "\")  '<== the 'name' is always follwed by '/' character

GetName = Mid(cell.value, iIni + 1, iEnd - iIni - 1)

End Function


Sub UpdateRngToDelete(baseRng As Range, toBeAddedRng As Range)

If baseRng Is Nothing Then
    Set baseRng = toBeAddedRng
Else
    Set baseRng = Union(baseRng, toBeAddedRng)
End If

End Sub


Function MyMatch(value As String, rng As Range) As Boolean

MyMatch = Not IsError(Application.Match(value, rng, 0))

End Function

答案 2 :(得分:14)

其中许多答案都有效,但我发现目前最简单的方法是通过ViewData或ViewBag发送数据,让JSON.Net对其进行序列化。

在页面加载之前需要Javascript生成或需要避免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反序列化支持较差。 相对于某些方法的另一个好处是,您可以使用浏览器View --> Source查看Javascript,因为它只是服务器端生成的文本。

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

答案 3 :(得分:6)

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

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

答案 4 :(得分:3)

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

      "SELECT table1.name, table2.ID FROM table1, table2"  
  or with an example
       da.SelectCommand = new SqlCommand("SELECT student.ime, student.prezime, studij.odjel, studij.smjer FROM student, studij", con);

答案 5 :(得分:2)

我想说这是你对数据建模方式的一个问题。不是使用字符串数组来表示地址,而是更清洁,更容易做到这样的事情:

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

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

答案 6 :(得分:1)

以下是您如何实现这一目标:

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

答案 7 :(得分:0)

JSON无论如何都是有效的JavaScript对象,当你自己打印JavaScript时,一旦转换为JSON,你就不需要对JSON进行编码/解码。

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

将打印以下内容,它是有效的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>

答案 8 :(得分:0)

对于一维数组

控制器:

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 = @Model.strArrayForJS;
        console.log(myArray); // [1, 2, 6, 7, 8, 18, 25, 61, 129]
        console.log(typeof (myArray)); //object
    });
</script>