简体   繁体   English

在Javascript读C#字典

[英]Reading C# dictionary in Javascript

I have a dictionary variable in C# (ASP.NET).我在 C# (ASP.NET) 中有一个字典变量。 I want to send this data to Javascript. I am using this code to serialize it and send to javascript.我想将此数据发送到 Javascript。我正在使用此代码将其序列化并发送到 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;在 Javascript 页面上,我用这个调用这个页面;

 $.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"} Chats var 中的值是{"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. ?我可以无论如何将其转换为二维数组并将其读取为数组 [0][0]、数组[1][0] 等吗?

Thanks.谢谢。

EDIT: One more confusion is that, the response object, returned from ASP.NET, contains编辑:另一个令人困惑的是,从 ASP.NET 返回的响应 object 包含

{"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.而不仅仅是预期{"Sam":"How are you?","Rita":"I am good"} And hence I have to split the response object by var Chats = response.split('\n')[0];因此,我必须将响应 object 拆分为var Chats = response.split('\n')[0]; which makes it an string!这使它成为一个字符串!

You read like this: 你读的是这样的:

alert(Chats["Sam"]);

(so like a C# Dictionary :-). (就像一个C#字典:-)。 You read/write to it using something like Chats["propertyName"] ) 你使用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#. 请注意,这与C#不同。 In C# c would contain a KeyValuePair<> containing both the key and the value. 在C#中, c将包含一个包含键和值的KeyValuePair<> In Javascript c is only the key and to get the value you have to use Chats[c] . 在Javascript中c只是关键,要获得你必须使用Chats[c]

(the reasoning for hasOwnProperty is here http://yuiblog.com/blog/2006/09/26/for-in-intrigue/ ) hasOwnProperty的推理在这里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]]);
    }
}

Just add the data type json to your ajax request 只需将数据类型json添加到您的ajax请求中即可

$.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 这将使response成为您可以像这样访问的javascript对象

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

I guess the important point here is that you properly understand what is going on on the JavaScript client side. 我想这里重要的一点是你正确理解了JavaScript客户端的情况。 The datatype that arrives on the JavaScript client side is a JSON string. 到达JavaScript客户端的数据类型是JSON字符串。 JSON (= JavaScript Object Notation) can directly be interpreted by JavaScript. JSON(= JavaScript Object Notation)可以直接由JavaScript解释。

A JavaScript object looks as follows: JavaScript对象如下所示:

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

You can access the properties of a JavaScript object either through a somewhat Dictionary-similar way like 您可以通过类似于字典的方式访问JavaScript对象的属性

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

or directly (property notation) 或直接(财产符号)

anObject.name

Instead a similar JSON string would look like 相反,类似的JSON字符串看起来像

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

Now to convert the JSON string to a JavaScript object you need to parse it. 现在要将JSON字符串转换为JavaScript对象,您需要解析它。 jQuery does this already for you, otherwise you can invoke JSON.parse(aJsonString) and you'll get a valid JavaScript object. jQuery已经为你做了这个,否则你可以调用JSON.parse(aJsonString) ,你将得到一个有效的JavaScript对象。

Here I did a quick example: http://jsbin.com/adejev/2/edit 在这里我做了一个简单的例子: http//jsbin.com/adejev/2/edit

For ASP.NET Core, I used this inside the cshtml file.对于 ASP.NET Core,我在cshtml文件中使用了它。 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.基本上我将整个字典重建为 Javascript。采用这种方法的原因是因为我在 Javascript 中有子函数,它们将无法调用服务器 model 函数,并在按键等事件上使用动态参数。

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:检查浏览器获取的 html 页面:

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';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM