0

I'm returning a object from controller to view, but it doesn't always work. It does not work when the object contains a list of objects, if the list is empty it works (the html rData3 is updated with text).

1 - The object that I'm returning:

public class Etiqueta
{
    public int Id { get; set; }
    public string Nombre { get; set; }
    public List<EtiquetaFoto> EtiquetasFotos { get; set; }
}

2 - The Controller:

public class FotosController : Controller
{   
    public JsonResult Etiqueta(string Id)
    {
        var sa = new JsonSerializerSettings();
        Etiqueta etiq = _context.Etiquetas.Where(x => (x.Id.ToString() == Id)).Include(x => x.EtiquetasFotos).First();
        return Json(etiq,sa);
    }
}

3 - The View:

<script type="text/jscript">
$("button").click(function () {
    var cID = $(this).attr('id');
    $.getJSON('/Fotos/Etiqueta/' + cID, function (data) {
        var items = "";      
        items += data.Id + " - " + data.Nombre;             
        $('#rData3').html(items);
    });
})
</script>

What I should do to it works when the object has the list EtiquetasFotos with data?

user3682831
  • 45
  • 1
  • 1
  • 5
  • What does `EtiquetaFoto` contain? Btw, you can simplify the query to the following: `await _context.Etiquetas.Include(x => x.EtiquetasFotos).FindAsync(Id)`. – Haytam Aug 24 '19 at 16:35

3 Answers3

0

I faced the same problem time ago.

At this point, I only know two options.

  • You can give back to the view a json serialized object. You can also give a json object from view to controller ( How to convert View Model into JSON object in ASP.NET MVC? ). I know that it's what you've tried. I think it doesn't work because from your controller you give back a Json object, and you want to display it as html, but I'm not very sure.

  • Also, you can load partial views using ajax. I think this is the better one. You can return a partial view with the data that you want to display inside, and then load it in the view using ajax.

return partial view -> ( How to Return partial view of another controller by controller? )

load it in the view -> ( Load PartialView with using jquery Ajax? )

I think that using this second option is when your line $('#rData3').html(items); is going to work.

I don't know if it is what you need, I hope it helps you ;)

0

I have seen that the problem is that the LINQ search returns an object, but wit circular references: An "Etiqueta" has a list of "EtiquetaFoto". Each "EtiquetaFoto" has an "Etiqueta" (and a "Foto"), and each "Etiqueta" has again another list of "EtiquetaFoto".

If I replace the nested "Etiqueta" by a new object, I breack the circular reference and the View can recive the data.

So, what is the best way of make the LINQ search?

user3682831
  • 45
  • 1
  • 1
  • 5
0

You can just add [JsonIgnore] annotation before the circular reference.

Jmel Becha
  • 154
  • 3