Error returning JSon data from the driver

0

I have the following code in my controller where I send the list of cities to a JsonResult

private ApplicationDbContext db = new ApplicationDbContext();
 //la linea anterior es donde instancio el modelo de datos o data context
    public JsonResult GetDataCiudades()
    {
        var CiudadesJson =  db.ciudad.ToListAsync(); // from model 

        return Json(CiudadesJson, JsonRequestBehavior.AllowGet);
    }

And when I try to return this JsonResult from the view I use the following code ...

else {
            $('#Ciudad').find('option').remove();
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetDataCiudades", "GenerarCertificado")',
                dataType: 'json',
                type: 'POST',
                data: "{}",
                contentType: 'application/json',
                success: function (data) {
                   var result = JSON.parse(data);
                    $.each(result, function (index, value) {
                        var option = $('<option value="' + index + '">' + value + '</option>');
                        $('#Ciudad').append(option);
                    });
                },
                error: function (data, status, jqXHR) {
                    alert('Error al cargar Ciudades.');
                }
            });
        }

But it returns a lot of objects and characters in the drop-down list that I'm showing in the view ....

What am I doing wrong?

    
asked by ger 14.12.2016 в 17:55
source

2 answers

0

I have had the same problem, and what has worked for me is changing the method:

public string GetDataCiudades()
{
    var CiudadesJson =  db.ciudad.ToListAsync(); // from model 

    return Newtonsoft.Json.JsonConvert.SerializeObject(CiudadesJson);
}

I am more confident in the outcome of the Newtonsoft.Json than in the native C # , but that is only in my experience. Hopefully this will help solve the problem.

    
answered by 08.03.2017 / 20:23
source
0

Based on this Json

{ dato1:
  { objeto:
    { 
      objeto1:"info",
      objeto2:"info",
      objeto3:"info"‌​
    }
  },
  dato2:"informaci‌​on",
  dato3:"informaci‌​on"
}

What you can do is go through the Json internal objeto: { ... }

success: function (data) {
  var result = JSON.parse(data);
  //este ciclo solo si necesitas los valores del objeto interno
  //este .each recorrerá únicamente el objeto interno
  $.each(result.objeto, function (index, value) {
    var option = $('<option value="' + index + '">' + value + '</option>');
    $('#Ciudad').append(option);
  });


  //suponiendo que necesitas todos los valores del Json
  $.each(result, function (index, value) {
    if(value.objeto != undefined){//validando que el value tenga un objeto
      //recorriendo el objeto interno
      $.each(value.objeto, function (index1, value1) {
        var option = $('<option value="' + index1 + '">' + value1 + '</option>');
        $('#Ciudad').append(option);
      });
    }
    var option = $('<option value="' + index + '">' + value + '</option>');
    $('#Ciudad').append(option);
  });
},

In case you throw error with result.objeto test with result[0].objeto

    
answered by 14.12.2016 в 18:49