I have a Web Application in ASP.Net Core 5, which consults a Web API in .Net core as well. This content that it returns in JSON format must be read from a File called landing.js. The problem is that the data reaches the variable (data) but I cannot access its methods, it always designs undefined
Will I be returning the results in String fine from the controller? it should actually arrive in JSON towards the JS.
my controller:
public async Task<IActionResult> GetPodcastLandingPortada()
{
List<PPodcast> ppodcastPortada = new List<PPodcast>();
string jsonresultado = "";
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://localhost:44379/api/Podcast/ObtenerPodcastPortadaPrincipal"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
//ppodcastPortada = JsonConvert.DeserializeObject<List<PPodcast>>(apiResponse);
jsonresultado = JsonConvert.DeserializeObject(apiResponse).ToString();
}
}
return Ok(jsonresultado);
}
my file landing.js
window.onload = function () {
_getPortadaPrincipal();
} function _getPortadaPrincipal() {
let ruta = '/podcast/GetPodcastLandingPortada';
$.ajax({
type: 'GET',
url: ruta,
contentType: JSON,
processData: false,
success: function (data) {
console.log(data.titulo); //this is where it returns undefinned, but the data variable is loaded
$("#portadaPrincipal").html(row);
console.log(data);
},
error: function () {
alert("Error en la carga de la Portada");
},
});
}
Firstly, you did a duplicated thing to return a json. So you just return Ok(apiResponse); and move it after string apiResponse = await response.Content.ReadAsStringAsync(); in the using:
using (var response = await httpClient.GetAsync("https://localhost:44379/api/Podcast/ObtenerPodcastPortadaPrincipal"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
return Ok(apiResponse);
}
Secondly, if you want to get the item value in json, you also need to convert json to object in js.
So the correct way to get the item in response should be like below:
public async Task<IActionResult> GetPodcastLandingPortada()
{
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("url"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<List<PPodcast>(apiResponse);
return Ok(model);
}
}
}
Then you can get the item:
console.log(data[0].xxx); //because what you return is an array