0

My problem is currently : How to pass a JSON Object (As it is or as a C# object deserialized with Newtonsoft.Json) to a javascript file.

I tried the following method :

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

but when the json file is rendered in HTML (as a html attribute) it stops on the quote character, i tried to escape it but it's not working either. So when in my javascript file i use JSON.parse() the syntax is not valid.

Problem Solved : - Declared a javascript variable Data in my .cshtml file, put the jsonfile as a @ViewBag element inside. - got it in my javascript by window.Data - parsing it as json, using it, magic done.

(Thanks for those who answered)

4
  • is the json_file the json string or the name of the file? Commented Nov 7, 2013 at 11:07
  • it's a string. (i opened a StreamReader and read it to the end and store it in a string). The json file is well formated i got my app to work with json files without quote characters. Commented Nov 7, 2013 at 11:14
  • do you have any ' or > in the json_file? Commented Nov 7, 2013 at 11:33
  • yes that's exactly the problem i'm describing. When i got json file with quotes it crashes when the json file is quotes free it works Commented Nov 7, 2013 at 11:37

5 Answers 5

1

If this is a json object, why not insert the object in a javascript variable on the page, as presumably you want to use the variable e.g. in Ajax?

function someThingClicked(){
  var myObject = <%= json_file %>;

  $.ajax({
    type: "POST",
    url: "SomeUrl",
    data: myObject,
    success: function () { },
    contentType: "application/json; charset=utf-8",
    dataType: "json"});
}

This should serve something like the below to the browser:

var myObject = {
  someField : 'someValue'
};
...

If you are using razor, you would write it out something like:

  var myObject = @Html.Raw(ViewBag.json_file);

Assuming that you've added the json_file string into ViewBag from your controller.

Sign up to request clarification or add additional context in comments.

Comments

1

in this case you can try use JsonResult

Comments

0

Try this please

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

Comments

0

it's a result of you concatenation results in termination of the valuesttribute value before you intended. E.g. you have a 'character in the json_file

as an example if the file contains

var x = 'this is a string'

then the result of your concatenation would yield invalid html

<input id='data' type='hidden' value='var x = 'this is a string'' />

notice that the value attribute is terminated after var x = and that the final "attribute" string is missing an = prior to the value (the empty string '')

to avoid that you should assign the json to a variable and then assign that value as the value to the input element

Response.Write(string.Concat("<input id='data' type='hidden'/>",
                             "<script>$(function(){var x = ", json_file,
                             ";$("#data").val(JSON.stringify(x));</script>");    

(assuming you are already using jQuery otherwise you'd have to do it with plain vanilla JS which is a little more work but can be done

Comments

0

An other solution instead of printing json string inside the html attribute

  1. Create an action that returns your json in your controller

    public string GetData()
    {
        //read your json file
        return json_file; //return your json string
    }
    
  2. On View side, put your input tag and fetch json_file through an ajax request

    <input id='data' type='hidden' />
    <script>
        $(function () {
            $.post("/yourControllerName/getData", {}, function (response) {
                $("#data").val(response);
            },'json');
        });
    </script>
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.