简体   繁体   English

将JSON文件传递给Javascript ASP.NET MVC4

[英]Pass JSON file to Javascript ASP.NET MVC4

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. 我目前的问题是:如何将JSON对象(原样或作为使用Newtonsoft.Json反序列化的C#对象)传递给javascript文件。

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. 但是当json文件以HTML格式呈现(作为html属性)时,它会停止在引号字符上,我试图逃避它,但它也无法正常工作。 So when in my javascript file i use JSON.parse() the syntax is not valid. 因此,当我在我的javascript文件中使用JSON.parse()时,语法无效。

Problem Solved : - Declared a javascript variable Data in my .cshtml file, put the jsonfile as a @ViewBag element inside. 解决问题: - 在我的.cshtml文件中声明了一个javascript变量数据,将jsonfile作为@ViewBag元素放入其中。 - got it in my javascript by window.Data - parsing it as json, using it, magic done. - 通过window.Data在我的javascript中获取它 - 将其解析为json,使用它,魔术完成。

(Thanks for those who answered) (感谢那些回答的人)

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 eg in Ajax? 如果这是一个json对象,为什么不在页面上的javascript变量中插入对象,因为大概你想在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. 假设您已从控制器json_file字符串添加到ViewBag

在这种情况下,您可以尝试使用JsonResult

it's a result of you concatenation results in termination of the value sttribute value before you intended. 它是您连接的结果导致在您预期之前终止value sttribute值。 Eg you have a ' character in the json_file 例如,你在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 那么连接的结果会产生无效的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 '' ) 请注意, value属性在var x =之后终止,并且最后的“attribute” string缺少值=之前的值(空字符串''

to avoid that you should assign the json to a variable and then assign that value as the value to the input element 为了避免你应该将json分配给变量,然后将该值作为值分配给input元素

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 (假设你已经在使用jQuery,否则你必须使用普通的香草JS这样做,这是一个更多的工作,但可以完成

请试试这个

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

An other solution instead of printing json string inside the html attribute 另一种解决方案,而不是在html属性中打印json字符串

  1. Create an action that returns your json in your controller 创建一个在控制器中返回json的操作

     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 在View端,输入您的输入标记并通过ajax请求获取json_file

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM