[英]C# server array to client / javascript
This has probably been asked before but I can't seem to find any answers that I can get to work. 这可能是以前问过的,但我似乎找不到任何可以解决的答案。
I have a SQL query that produces five rows of data in the backend. 我有一个SQL查询,该查询在后端产生五行数据。 And I then fetch the data from the query like so: 然后,我从查询中获取数据,如下所示:
if (reader.HasRows) {
var list = new List < GetUserNames > ();
// Read advances to the next row.
while (reader.Read()) {
//Person p = new Person();
// To avoid unexpected bugs access columns by name.
//Convert.ToInt32(dataReader.GetValue(3));
wholeAvg = Decimal.Round(reader.GetDecimal(reader.GetOrdinal("wholeavg")), 2);
list.Add(new GetUserNames {
users = reader.GetString(2)
});
allRecords = list.ToArray();
}
}
Now what I would like to send to the client and use with javascript is the allRecords array. 现在,我想发送给客户端并与javascript一起使用的是allRecords数组。 Can someone point me in the right direction how to get the array from the backend? 有人可以指出正确的方向如何从后端获取阵列吗?
Thanks! 谢谢!
如果使用的是MVC,则可以将'allrecords'添加到TempData并使用以下代码;
var records = @Html.Raw(Json.Encode(TempData["Records"]))
You could serialize it to JSON then store the value in a hidden input. 您可以将其序列化为JSON,然后将值存储在隐藏的输入中。 In your javascript you can then pick up the value of that field: 然后,您可以在JavaScript中获取该字段的值:
.cs: .cs:
var json = JsonConvert.SerializeObject(allRecords);
hdUsers.Value = json;
.aspx: .aspx:
<asp:HiddenField runat="server" ID="hdUsers"/>
<script type="text/javascript">
var jsonString = $("[id$='hdUsers']").val()
var arr = JSON.parse(jsonString);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.