0

I'm trying to convert an IEnumerable model to Json array in my view via jQuery as below:

@model IEnumerable<SamsungTools.Models.SaleCenter>

var arr = @Html.Raw(Json.Encode(Model))

But an error raised as:

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.SaleCenter_7A0CE6A0DDE13787CC1DADED551C4B390761E2E4BC6E0E6F5B8DF894725F4934'.

What's wrong in my code?

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
Mehdi
  • 499
  • 1
  • 7
  • 31
  • 3
    The issue isn’t with your code but with your data which contains a circular reference, e.g. in your model hierarchy one item A references item B, item B references item A again or an item C which references item A. – ckuri Feb 28 '19 at 19:08
  • 1
    Check if this can help: https://stackoverflow.com/a/23490311/2348125 – Amir Molaei Feb 28 '19 at 19:30
  • 1
    Possible duplicate: [Circular reference detected exception while serializing object to JSON](https://stackoverflow.com/q/16949520/3744182). – dbc Mar 01 '19 at 05:36
  • Thanks @ckuri, it helps to solve the problem. – Mehdi Mar 01 '19 at 08:23

1 Answers1

0

Thanks to @ckuri, Solved by creating a new view model with specified properties and pass a list of it to view. In new view model I removed two properties which were caused self referencing circular loop in JSon convert.

Finally, Model:

public class SaleCenterViewModel
{
    public string Title { get; set; }
    public string TitleEN { get; set; }
    public int Code { get; set; }
    public string Lat { get; set; }
    public string Lng { get; set; }
    public string Phone { get; set; }
    public string Address { get; set; }
    public string AddressEN { get; set; }
    public static SaleCenterViewModel Set(SaleCenter saleCenter)
    {
        return new SaleCenterViewModel
        {
            Title = saleCenter.Title,
            TitleEN = saleCenter.TitleEN,
            Code = saleCenter.Code,
            Lat = saleCenter.Lat,
            Lng = saleCenter.Lng,
            Phone = saleCenter.Phone,
            Address = saleCenter.Address,
            AddressEN = saleCenter.AddressEN
        };
    }
}

Store:

public List<SaleCenterViewModel> GetAllSaleCenters()
{
    return
        db.SaleCenters
        .Select(SaleCenterViewModel.Set)
        .ToList();
}

Controller:

public ActionResult Map()
{
    GeneralStore gs = new GeneralStore();
    ViewData["Cities"] = gs.GetCitiesHaveSaleCenter();
    ViewData["Areas"] = gs.GetAllAreas();
    var saleCenters = gs.GetAllSaleCenters();
    return View(saleCenters);
}

View:

@model List<SamsungTools.ViewModels.SaleCenterViewModel>

<script>
    var arr = @Html.Raw(Json.Encode(Model))
</script>
Mehdi
  • 499
  • 1
  • 7
  • 31