从C#发送类似JSON的字符串到javascript [英] Sending a string like JSON from C# to javascript

查看:79
本文介绍了从C#发送类似JSON的字符串到javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JavaScript 中有一些代码,如下所示:

I have some code in JavaScript like this:

slider.setPhotos([
    { "src": "image1", "name": "n1" },
    { "src": "image2", "name": "n2" },
    { "src": "image3", "name": "n3" }
    ]);

我想设置 src 和名称来自 C#

假设值是像这样在 C#

var images = new string[] {"/images/a1.jpg", "/images/a2.jpg", "/images/a3.jpg"};

var names = new string[] {"First", "Second", "Third"};

如何将这些值设置为 JavaScript 代码(即在C#代码中的Page Load方法)?

How can I set these values into JavaScript code (i.e. in Page Load method in C# code)?

推荐答案

在服务器上,您需要将数据序列化为JSON然后您可以使用类似隐藏输入字段的内容将其作为HTML写入响应。

On the server you need to serialize the data as JSON and then you can write it into the response as HTML using something like a hidden input field.

例如,您可以使用 NewtonSoft 用于序列化JSON的JSON库(内置于 ASP MVC 4 然而使用Nuget很容易安装)

For example you might use the NewtonSoft JSON library to serialize the JSON (which is built into ASP MVC 4 however is easy to install using Nuget)

string json = Newtonsoft.Json.JsonConvert.SerializeObject(images);

然后将json渲染成HTML(有很多方法可以做到这一点)
例如

Then render the json into the HTML (there are number of methods to do this) e.g.

Response.Write(string.Concat("<input id='data' type='hidden' value='", json, "' />");

HiddenField jsonField = new HiddenField
{
    ID = "data"
};
jsonField.Value = json;
this.Controls.Add(jsonField);

甚至直接写作脚本跳过需要解析客户端(我仍然倾向于使用HTML方法来避免回发/更新面板的任何问题导致脚本多次执行)

or even write directly as script skipping the need to parse on the client (I still tend to use the HTML method to avoid any issues with Postbacks/Update Panels causing the script to be executed multiple times)

Response.Write(string.Concat("<script type='text/javascript'> var images = ", json, ";</script>");

在客户端上,您可以从HTML中读取此JSON并进行解析。在现代浏览器中,这是内置的,或者你可以polyfil我喜欢 JSON2

On the client you can then read this JSON from the HTML and parse it. In modern browsers this is built in, or you can polyfill with something like JSON2

例如

var field = document.getElenentById('data');
var images = JSON.parse(field.value);

然后您可以将数据作为Javascript对象访问。

You then have access to the data as a Javascript object.

这篇关于从C#发送类似JSON的字符串到javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆