Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  88] [ 1]  / answers: 1 / hits: 37320  / 13 Years ago, sat, october 15, 2011, 12:00:00

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!


More From » jquery

 Answers
5

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]]);
}
}

[#89601] Thursday, October 13, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mustafaericho

Total Points: 322
Total Questions: 103
Total Answers: 110

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
mustafaericho questions
Mon, May 31, 21, 00:00, 3 Years ago
Sun, May 23, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
;