简体   繁体   中英

Passing Array to JAVAScript from c# controller

I am building on object list in c# and returning it as return Json(thisVar) from my controller as public async Task<JsonResult> Then in my CSHTML I have this:

$.get(url,
      dataObject, 
      function (response) {
         alert(response);
         var allRes = JSON.parse(response);

my first alert show [object Object]

but get an error:

Uncaught SyntaxError: Unexpected token o in JSON at position 1

Your response is already an object - there is no need to parse it.

...
function (response) {
    var arr = response.riskPoint;
    for(var i = 0;i<arr.length;i++){
        // read arr[i];
    }

}

If your 1st alert showing a JS object then your object is already JSON parsed and you don't need to JSON.parse

The server probably returns the array wrapped in an object, like response.thisVar, if you do console.log you'll find it

Correct answer was that It was already jsoon so I needed to loop through and just use the json object. I had to use labels in [] for the field names Thanks for all the answers. console.log was especially helpful

JSON.parse() is to convert text into a JavaScript object, not vice-versa.

Can you recheck your code? The response is already a JSON. JSON.stringify will help you to print it to text.

eg:

`var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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