将像 JSON 这样的字符串从 C# 发送到 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11625917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:51:29  来源:igfitidea点击:

Sending a string like JSON from C# to javascript

c#javascriptstringobject

提问by MSajjadi

I have some code in JavaScriptlike this:

我有一些这样的代码JavaScript

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

And I want to set the values of srcand namefrom C#.

我想设置srcnamefrom的值C#

Assume values are like this in C#:

假设值是这样的C#

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

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

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

如何将这些值设置为JavaScript代码(即在 C# 代码中的页面加载方法中)?

回答by Chris Herring

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.

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

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

例如,您可以使用NewtonSoftJSON 库来序列化 JSON(它内置在ASP MVC 4 中,但使用 Nuget 很容易安装)

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

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

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

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

or

或者

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

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)

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

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

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

在客户端上,您可以从 HTML 中读取此 JSON 并对其进行解析。在现代浏览器中,这是内置的,或者您可以使用JSON2 之类的东西进行polyfill

e.g.

例如

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

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

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

回答by yogi

Assuming that imagesand namesare of same length You can use this

假设imagesnames的长度相同 你可以使用这个

StringBuilder str = new StringBuilder();

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

str.AppendLine("slider.setPhotos([");
for(int i=0; i< images.Length; i++)
{
   str.AppendLine("{ \"src\": "+ images[i] +", \"name\": "+ names[i] +" }");
   str.AppendLine( (i==images.Length-1 ? "]);":","));
}

Page.ClientScript.RegisterClientScriptBlock(
               this.GetType(), "Key007", str.ToString(), true);

This code will insert a script block when your page will be loaded and after that you can use that script block anywhere in your client side code.

此代码将在您的页面加载时插入一个脚本块,之后您可以在客户端代码的任何位置使用该脚本块。