Sending a string like JSON from C # to javascript

I have code in the JavaScriptfollowing:

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

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

Assume values ​​such as C#:

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

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

How to set these values ​​in code JavaScript(i.e. in the method of loading a page in C # code)?

+5
source share
2 answers

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

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

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

json HTML ( ) .

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

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

script, ( HTML, - Postbacks/Update, script)

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

JSON HTML . polyfill - JSON2

.

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

Javascript.

+6

, images names

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

script, , script .

+2

All Articles