How to pass Datarow array of values to javascript
I've Datarow Collection Array of strings.I want to pass this array to jav开发者_Python百科ascript and do operations on them.How do I do this
I recommend to make use of DataContractJsonSerializer
.
Here is a simple function that will turn any serializable object into JSON:
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
public static string ToJson<T>(this T input)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, input);
var jsonText = Encoding.UTF8.GetString(stream.ToArray());
return jsonText;
}
}
Here is an example where I used it on a string[]
:
static void Main()
{
var input = new[] { "one", "two", @"three ""with quotes""!", "↑" };
Console.WriteLine(input.ToJson());
Console.ReadLine();
}
The output is, as expected:
["one","two","three \"with quotes\"!","↑"]
Now, in your question you mention DataRow
, so you need to turn a DataRow
object into something you can pass in here. I think the ItemArray
property is what you are looking for:
public string DataRowToJson(DataRow dr)
{
return dr.ItemArray.ToJson();
}
There's nothing stopping you using ASP.NET controls for things other than HTML. I regularly find myself using repeaters to create Javascript arrays.
<script type="text/javascript">
<asp:Repeater ID="WhateverRepeater" runat="server">
<HeaderTemplate>
var data = [
</HeaderTemplate>
<ItemTemplate>"<%# Container.DataItem %>"</ItemTemplate>
<SeparatorTemplate>,
</SeparatorTemplate>
<FooterTemplate>
];
</FooterTemplate>
</asp:Repeater>
</script>
Bind your data to that repeater and it'll dump out a Javascript array, like so:
var data = [
"string0",
"string1",
"string2",
"string3"
];
You can then use this in your client-side code like any other JS array.
(Doing this without a compiler present, so some of the details may be off)
精彩评论