16

I have a dictionary variable in C# (ASP.NET). I want to send this data to Javascript. I am using this code to serialize it and send to javascript.

Dictionary<string, string> chat;
chat = new Dictionary<string, string>();

chat.Add("Sam", "How are you?");
chat.Add("Rita", "I am good");
var serialize = new System.Web.Script.Serialization.JavaScriptSerializer();

Response.Write(serialize.Serialize(chat));

On the Javascript page, I am calling this page using this;

 $.ajax({
 url: "TextChatCalls/getChat.aspx",
 type: "POST",
 context: document.body,
 success: function (response) {
          var Chats = response.split('\n')[0];
          alert(Chats);

          }
 });

The value in Chats var is {"Sam":"How are you?","Rita":"I am good"}

I don't know how do I read this value in Chats. Can I anyhow convert this into a 2D array and read it as array[0][0], array[1][0] etc. ?

Thanks.

EDIT: One more confusion is that, the response object, returned from ASP.NET, contains

{"Sam":"How are you?","Rita":"I am good"}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
    <form name="form1" method="post" action="getChat.aspx?Id=141755" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZJctiKZK4rXVndR3mbGssIarCrOF" />
</div>

    <div>

    </div>
    </form>
</body>
</html>

And not just {"Sam":"How are you?","Rita":"I am good"} as expected. And hence I have to split the response object by var Chats = response.split('\n')[0]; which makes it an string!

4 Answers 4

30

You read like this:

alert(Chats["Sam"]);

(so like a C# Dictionary :-). You read/write to it using something like Chats["propertyName"])

or, to go through each value:

for (var c in Chats)
{
    if (Chats.hasOwnProperty(c)) 
    {
        alert(c + '   ' + Chats[c]);
    }
}

Note that this is different than C#. In C# c would contain a KeyValuePair<> containing both the key and the value. In Javascript c is only the key and to get the value you have to use Chats[c].

(the reasoning for hasOwnProperty is here http://yuiblog.com/blog/2006/09/26/for-in-intrigue/)

Now... If you really want to split it:

var array = [];

for (var c in Chats)
{
    if (Chats.hasOwnProperty(c)) 
    {
        array.push([c, Chats[c]]);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I can't understand why, but my response object contains this value "{"Sam":"How are you?","Rita":"I am good"} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="w3.org/1999/xhtml"> <head><title> </title></head> <body> <form name="form1" method="post" action="getChat.aspx?Id=141755" id="form1"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZJctiKZK4rXVndR3mbGssIarCrOF" /> </div> <div> </div> </form> </body> </html> "
@Joy You have to do a Response.End() after the Response.Write(), otherwhise you'll send the whole aspx page after the JSON :-)
Better still you should be using an ashx handler or a page method. There's no point going through the aspx lifecycle if you're not going to output the page content.
3

Just add the data type json to your ajax request

$.ajax({
 url: "TextChatCalls/getChat.aspx",
 type: "POST",
 dataType: "json"
 context: document.body,
 success: function (response) {
          // do something with response
 });

This will make response a javascript object that you can access like this

alert(response["sam"]) //How are you?

to split that up into a 2d array just do this

var Chats = [];
for ( k in response ){
  Chats[Chats.length] = [k, response[k]];
}

Comments

3

I guess the important point here is that you properly understand what is going on on the JavaScript client side. The datatype that arrives on the JavaScript client side is a JSON string. JSON (= JavaScript Object Notation) can directly be interpreted by JavaScript.

A JavaScript object looks as follows:

var anObject = { name: "Sam", surname: "abc"};

You can access the properties of a JavaScript object either through a somewhat Dictionary-similar way like

anObject["name"] //will get "Sam"

or directly (property notation)

anObject.name

Instead a similar JSON string would look like

var aJsonString = '{ "name": "Sam", "surname": "abc"}'

Now to convert the JSON string to a JavaScript object you need to parse it. jQuery does this already for you, otherwise you can invoke JSON.parse(aJsonString) and you'll get a valid JavaScript object.

Here I did a quick example: http://jsbin.com/adejev/2/edit

Comments

0

For ASP.NET Core, I used this inside the cshtml file. Basically I rebuilt the entire Dictionary into Javascript. The reason for this approach is because I have subfunctions in Javascript that won't be able to call the server model functions with dynamic parameters on events like keypress.

var ModelZxcvWarnLookup = {};
@foreach (var kvp in Model.View.ZxcvbnWarningMsgLocalization)
{
    @:ModelZxcvWarnLookup['@Html.Raw(@kvp.Key)'] = '@Html.Raw(@kvp.Value)';
}

Inspecting the html page fetched by the browser:

var ModelZxcvWarnLookup = {};
ModelZxcvWarnLookup["Straight rows of keys are easy to guess"] = "Chinese Straight rows of keys are easy to guess";
ModelZxcvWarnLookup["Short keyboard patterns are easy to guess"] = "Chinese Short keyboard patterns are easy to guess";
ModelZxcvWarnLookup['Repeats like "aaa" are easy to guess'] = 'Repeats like "aaa" are easy to guess';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.