Reputation: 157
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)
Upvotes: 0
Views: 2797
Reputation: 2685
Create an action that returns your json in your controller
public string GetData()
{
//read your json file
return json_file; //return your json string
}
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>
Upvotes: 0
Reputation: 21742
it's a result of you concatenation results in termination of the value
sttribute 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
Upvotes: 0
Reputation: 2685
Try this please
Response.Write(string.Concat("<input id='data' type='hidden' value=\"", json_file.Replace('\"', '\''), "\" />"))
Upvotes: 0
Reputation: 107277
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.
Upvotes: 1