在 Javascript 中读取 C# 字典

发布于 2024-12-10 00:42:54 字数 1647 浏览 1 评论 0原文

我在 C# (ASP.NET) 中有一个字典变量。我想将这些数据发送到 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));

在 Javascript 页面上,我使用 this 调用此页面;

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

          }
 });

Chats var 中的值是 {"Sam":"How are you?","Rita":"I am good"}

我不知道如何在 Chats 中读取此值。我可以将其转换为二维数组并将其读取为 array[0][0]、array[1][0] 等吗?

谢谢。

编辑: 另一个令人困惑的是,从 ASP.NET 返回的响应对象

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

不仅包含 {"Sam":"How are you?","Rita":"I am good"} 作为预期的。因此,我必须通过 var Chats = response.split('\n')[0]; 拆分响应对象,使其成为一个字符串!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

挽心 2024-12-17 00:42:54

您可以这样阅读:(

alert(Chats["Sam"]);

就像 C# 字典一样:-)。您可以使用诸如 Chats["propertyName"]) 之类的方式对其进行读/写

,或者遍历每个值:

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

请注意,这与 C# 不同。在 C# 中,c 将包含一个包含键和值的 KeyValuePair<>。在 Javascript 中,c 只是键,要获取值,您必须使用 Chats[c]

hasOwnProperty 的推理在这里 http://yuiblog.com /blog/2006/09/26/for-in-intrigue/

现在...如果你真的想分割它:

var array = [];

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

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]]);
    }
}
八巷 2024-12-17 00:42:54

只需将数据类型 json 添加到您的 ajax 请求中

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

这将使 response 成为一个 javascript 对象,您可以像这样访问它,

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

将其拆分为 2d 数组,只需执行以下操作

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

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]];
}
梦旅人picnic 2024-12-17 00:42:54

我想这里重要的一点是你正确理解 JavaScript 客户端发生了什么。到达 JavaScript 客户端的数据类型是 JSON 字符串。 JSON(= JavaScript 对象表示法)可以直接由 JavaScript 解释。

JavaScript 对象如下所示:

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

您可以通过类似于字典的方式

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

或直接访问 JavaScript 对象的属性(属性表示法)

anObject.name

相反,类似的 JSON 字符串将如下所示

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

现在将 JSON 字符串转换为 JavaScript 对象需要解析它。 jQuery 已经为您完成了此操作,否则您可以调用 JSON.parse(aJsonString) 并且您将获得一个有效的 JavaScript 对象。

在这里我做了一个简单的例子: http://jsbin.com/adejev/2/edit

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

你与昨日 2024-12-17 00:42:54

对于 ASP.NET Core,我在 cshtml 文件中使用了它。基本上我将整个字典重建为 Javascript。采用这种方法的原因是因为我在 Javascript 中有子函数,它们无法在按键等事件上使用动态参数调用服务器模型函数。

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

检查浏览器获取的 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';

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';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文