Reputation: 126
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:
The user loads well
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
Upvotes: 1
Views: 153
Reputation: 12629
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);
Upvotes: 1