Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

60
Vistas
Parse return value from $ajax call in JavaScript from MVC Controller

I'm using VS2022 with C# and I'm trying to use an $ajax get method in my JavaScript function. I'm sending a parameter and returning a string[] list but when I receive the return I use JSON.stringify but when I try to use JSON.Parse it fails. The Javascript code is

$.ajax({
    type: "GET",
    url: '/Home/GetCategories/',
    contentType: 'application/json', 
    datatype: 'json',
    data: { ctgData: JSON.stringify(relvalue)}
}).done(function(result) {
    let userObj = JSON.stringify(result); 
    let resultList = JSON.parse(userObj);
});

The code in the controller which returns the list is simple at the moment until I get the return working

[HttpGet]
public ActionResult GetCategories(string ctgData)
{
    string[] categoryList = { "Food & Drink", "Sport & Fitness", "Education", "Housework", "Fiction", "Horror Books", "Fantasy", "Magic" };
    return Json(new { data = categoryList });
}

The value in result is

{"data":["Food & Drink","Sport & Fitness","Education","Housework","Fiction","Horror Books","Fantasy","Magic"]}

I've tried a number of different ways in Parse but it always fails, can you tell me what I'm missing to get my resultList to contain the string array.

7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You don' t need to parse anything. It is already java script object

$.ajax({
    type: "GET",
    url: '/Home/GetCategories/',
    contentType: 'application/json', 
    datatype: 'json',
    data: { ctgData: JSON.stringify(relvalue)}
     sucess:  function(result) {
      let data=result.data; // data = ["Food & Drink","Sport & Fitness",..]
   }
});
7 months ago · Juan Pablo Isaza Denunciar

0

use this:

JSON.parse(JSON.stringify(data))

const data = {"data":["Food & Drink","Sport & Fitness","Education","Housework","Fiction","Horror Books","Fantasy","Magic"]}

const resultJSON = JSON.parse(JSON.stringify(data))

console.log("json >>>", resultJSON)

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos