Nick
Nick

Reputation: 892

Sending JSON from C# to JavaScript

If I am using JSON to serialize an object in C# what is the best/easiest way to send it from C#, receive it in Javascript and deserialize it in JS?

Right now I am trying this but it doesn't seem to work

C#

json = JsonConvert.SerializeObject(X);
ClientScript.RegisterArrayDeclaration("data", json);
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "id", "testFunc()", true);

JS

var data;
function testFunc() {
   d3.select("#stuff").append("h3").text(data.source);
}

EDIT To clarify 'doesn't work'. I walk through the C# code sending the json and the string sent looks like this

"{\"target\":0,\"source\":1}"

I send it to the above javascript and it prints nothing to my page.

I looked at the browsers debugger and saw this line

var data =  new Array({"target":0,"source":1});

So, from my limited knowledge for some reason the data is being sent to the var in JS, not as a string but as a new array.

So I changed my JS to

var data;
function testFunc() {
    d3.select("#stuff").append("h3").text("Source: " + data[0].source + " Target " + data[0].target);
}

And voila the values printed out but why doesn't the var receive the JSON string as the C# sent? How can I get it to just send the string so I can parse it using JSON.parse()? I want to eventually send a whole list of objects and it will be easier to have the data arrive as the intended JSON string.

Upvotes: 4

Views: 3886

Answers (1)

poke
poke

Reputation: 387517

why doesn't the var receive the JSON string as the C# sent?

Because you told it to build an array with your JSON string as the content:

ClientScript.RegisterArrayDeclaration("data", json);

Instead, create the variable yourself and register it using RegisterClientScriptBlock:

string script = "var data = " + json + ";";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "dataVar", script, true);

Upvotes: 4

Related Questions