2011-10-15 13 views
8

Ho una variabile di dizionario in C# (ASP.NET). Voglio inviare questi dati a Javascript. Sto usando questo codice per serializzarlo e inviarlo a javascript.Lettura del dizionario C# in 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)); 

Nella pagina di Javascript, sto chiamando questa pagina utilizzando questo;

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

      } 
}); 

Il valore in Chat var è {"Sam":"How are you?","Rita":"I am good"}

Non so come faccio a leggere questo valore nelle chat. Posso comunque convertire questo in un array 2D e leggerlo come array [0] [0], array [1] [0] ecc.?

Grazie.

EDIT: Una più confusione è che, l'oggetto risposta, è tornato da ASP.NET, contiene

{"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> 

E non solo {"Sam":"How are you?","Rita":"I am good"} come previsto. E quindi devo dividere l'oggetto risposta di var Chats = response.split('\n')[0]; che lo rende una stringa!

risposta

19

Hai letto in questo modo:

alert(Chats["Sam"]); 

(così come un dizionario di C# :-). Hai letto/scrittura ad esso utilizzando qualcosa di simile Chats["propertyName"])

o, per passare attraverso ogni valore:

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

Si noti che questo è diverso da C#. In C# c conterrebbe un KeyValuePair<> contenente sia la chiave che il valore. In Javascript c è solo la chiave e per ottenere il valore è necessario utilizzare Chats[c].

(il ragionamento per hasOwnProperty è qui http://yuiblog.com/blog/2006/09/26/for-in-intrigue/)

Ora ... Se davvero si vuole dividerlo:

var array = []; 

for (var c in Chats) 
{ 
    if (Chats.hasOwnProperty(c)) 
    { 
     array.push([c, Chats[c]]); 
    } 
} 
+0

non riesco a capire il motivo per cui, ma il mio oggetto di risposta contiene questo valore "{" Sam ":" Come stai " 'Rita?':" Io sono buono "}

" – Jayesh

+2

@Joy Devi fare un 'Response.End()' dopo la ' Response.Write() ', altrimenti spedirai l'intera pagina aspx dopo JSON :-) – xanatos

+2

Grazie. Ha funzionato. – Jayesh

3

basta aggiungere il tipo di dati JSON per la richiesta ajax

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

Questo renderà response un oggetto JavaScript che è possibile accedere in questo modo

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

per dividere che fino in una matrice 2D solo fare questo

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

Credo che il punto importante qui è che si capisce correttamente cosa sta succedendo acceso sul lato client JavaScript. Il tipo di dati che arriva sul lato client JavaScript è una stringa JSON. JSON (= JavaScript Object Notation) può essere interpretato direttamente da JavaScript.

oggetto

Un JavaScript appare come segue:

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

è possibile accedere alle proprietà di un oggetto JavaScript sia attraverso un modo un po 'Dizionario-simile come

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

o direttamente (notazione proprietà)

anObject.name 

Invece una stringa JSON simile sarebbe simile a

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

Ora per convertire la stringa JSON in un oggetto JavaScript è necessario analizzarlo. jQuery fa già questo per te, altrimenti puoi invocare JSON.parse(aJsonString) e otterrai un oggetto JavaScript valido.

Qui ho fatto un rapido esempio: http://jsbin.com/adejev/2/edit