Sending a string like JSON from C# to javascript

后端 未结 2 864
心在旅途
心在旅途 2021-01-05 20:58

I have some code in JavaScript like this:

slider.setPhotos([
    { \"src\": \"image1\", \"name\": \"n1\" },
    { \"src\": \"image2\", \"name\":         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-05 21:52

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

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

    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.

提交回复
热议问题