Home > front end >  Problem with a select converting to a List ASP.Net Core 6 MVC
Problem with a select converting to a List ASP.Net Core 6 MVC

Time:08-24

I have the following code

public async Task<JsonResult?> Edit(int? id)
{
    if (id == null || _context.Users == null)
    {
        return null;
    }

    var user = await _context.Users.Where(u => u.UserId == id).FirstOrDefaultAsync();
    var securities = _context.UsersSecurities.Where(x => x.UserId == id).ToList();

    //var expected = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { user = Json(user), securities = Json(securities) }));
    if (user == null)
    {
        return null;
    }
    return Json(user);
}

In that function i receive an id an with that find an user by it primarykey UserID, and then search into the UsersSecurities model to search rows with that UserID (It is a relationship inside the database), well... i return a Json to the Ajax function that calls it... watch teh debugger view:
Yes
The user loads well


Now watch the usersecurities variable

enter image description here


The variable loads well and transform it into a list, all good until here but and i only return the user variable with Json() transform but in the JavaScript appear this error:

enter image description here
That error started when i append the Select of the UserSecurities, and when a user don't have any UserSecurities record it works well, i don't know what it's happening with that, it is just... strange, somebody help me please, i just wanna convert the user with their usersecurities into a json to return it

CodePudding user response:

From your User image, it has Securities loaded. If you expand those Securities you will find User object and so on. Thus it is going to be infinite Reference loop.

You can fix this behavior in your response with below configuration. You can append AddNewtonsoftJson configuration to services.AddMvc or services.AddControllers or services.AddControllersWithViews

// Append AddNewtonsoftJson with AddMvc or AddControllers or AddControllersWithViews, based on what you have used.
// services.AddMvc()
// services.AddControllersWithViews()
services.AddControllers()
    .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
  • Related