如何将 C# List<string[]> 转换为 Javascript 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18470702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a C# List<string[]> to a Javascript array?
提问by bynary
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"]]
How am I supposed to get this serialized string residing in a razor model into a javascript array?
我应该如何将这个位于剃刀模型中的序列化字符串放入 javascript 数组中?
采纳答案by Dustin Kingen
You could directly inject the values into JavaScript:
您可以直接将值注入 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:
或者,您可以通过 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
回答by Jedediah
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:
这将为您提供如下所示的 JSON:
[{"Address1" : "123 Easy Street", "CityName": "New York", "StateCode": "NY", "ZipCode": "12345"}]
回答by Akash Kava
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.
无论如何,JSON 都是有效的 JavaScript 对象,当您打印 JavaScript 本身时,一旦将其转换为 JSON,您就不需要进一步编码/解码 JSON。
<script type="text/javascript">
var addresses = @Html.Raw(Model.Addresses);
</script>
Following will be printed, and it is valid JavaScript Expression.
将打印以下内容,它是有效的 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>
回答by Charles Burns
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.
其中许多答案确实有效,但我发现迄今为止最简单的方法是通过 ViewData 或 ViewBag 发送数据并让 JSON.Net 对其进行序列化。
I use this technique when Javascript is needed for HTML generation before the page load or when AJAX overhead needs to be avoided:
当页面加载之前需要 Javascript 生成 HTML 或需要避免 AJAX 开销时,我会使用此技术:
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.
您始终可以依赖 JSON.NET,而某些浏览器的 JSON 反序列化支持较差。与某些方法相比的另一个好处是,您可以使用浏览器的 来查看 Javascript View --> Source
,因为它只是在服务器端生成的文本。
Note that In most situations, Web API a more elegant way to get JSON to the client.
请注意,在大多数情况下,Web API 是一种将 JSON 传递给客户端的更优雅的方式。
回答by Mehul Bhalala
Many way to Json Parse but i have found most effective way to
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>
回答by Hashim Akhtar
For those trying to do it without using JSON, the following is how I did it:
对于那些试图在不使用 JSON 的情况下做到这一点的人,以下是我的做法:
<script>
var originalLabels = [ '@Html.Raw(string.Join("', '", Model.labels))'];
</script>
回答by John81
This worked for me in ASP.NET Core MVC.
这在 ASP.NET Core MVC 中对我有用。
<script type="text/javascript">
var ar = @Html.Raw(Json.Serialize(Model.Addresses));
</script>
回答by Ahmed Elbendary
Here's how you accomplish that:
以下是您如何做到这一点:
//View.cshtml
<script type="text/javascript">
var arrayOfArrays = JSON.parse('@Html.Raw(Json.Encode(Model.Addresses))');
</script>
回答by Adel Mourad
For one dimension array
对于一维数组
Controller:
控制器:
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
View:
看法:
<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>