最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Sending a string like JSON from C# to javascript - Stack Overflow

programmeradmin3浏览0评论

I have some code in JavaScript like this:

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

And I want to set the values of src and name from C#.

Assume values are like this in 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 JavaScript code (i.e. in Page Load method in C# code)?

I have some code in JavaScript like this:

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

And I want to set the values of src and name from C#.

Assume values are like this in 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 JavaScript code (i.e. in Page Load method in C# code)?

Share Improve this question edited Jul 24, 2012 at 7:22 Marijn 10.6k5 gold badges61 silver badges81 bronze badges asked Jul 24, 2012 at 7:16 MSajjadiMSajjadi 3,8393 gold badges25 silver badges20 bronze badges 1
  • 1 How about simply using ajax to fetch this for you? – Jibi Abraham Commented Jul 24, 2012 at 7:23
Add a ment  | 

2 Answers 2

Reset to default 8

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.

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

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, "' />");

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)

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

e.g.

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

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

Assuming that images and names are of same length You can use this

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.

发布评论

评论列表(0)

  1. 暂无评论