Edit: The reason this error occurred was that in my _Layout.cshtml, I had written a link that referred to this actionmethod as Html.Action() instead of Html.ActionLink()...
I am building a website in MVC5 with EF6.1.3. I get the following exception when passing a collection of Project to a view:
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
The ActionMethod gets called an infinite amount of times.
I searched around and it appears that I get a reference loop in the Json serializer.
So I added [JsonIgnore]
to the fields in Project that has a reference back to Project. I also added the following to Global.asax:
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter
.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
Still no difference. I also tried to set the navigation properties that references back to Project to null, still no difference. That makes me think that maybe there is something else going on.
Code that generates error:
public ActionResult Index()
{
return View(db.Projects.Include(p => p.ProjectMissingPeople).ToList());
}
Project.cs:
public class Project
{
public int ProjectID { get; set; }
public string ProjectName { get; set; }
public string ProjectDescription { get; set; }
public string ProjectImageUrl { get; set; }
[JsonIgnore]
public string FounderId { get; set; }
[ForeignKey("FounderId")]
[JsonIgnore]
public ApplicationUser Founder { get; set; }
public ICollection<ProjectMissingPeople> ProjectMissingPeople { get; set; }
}
ProjectMissingPeople.cs:
public class ProjectMissingPeople
{
public int ProjectMissingPeopleID { get; set; }
public string Text { get; set; }
public bool Open { get; set; }
[JsonIgnore]
public int ProjectID { get; set; }
[JsonIgnore]
public Project Project { get; set; }
}
Index.cshtml:
@model IEnumerable<ProjectStockholm.BusinessModels.Project>
@foreach(var project in Model)
{
@Html.Partial("_ProjectThumbnail", project)
}
ProjectThumbnail.cs:
@model ProjectStockholm.BusinessModels.Project
<div class="project-thumbnail">
<img url="@Model.ProjectImageUrl" />
<h2>@Model.ProjectName</h2>
<p>@Model.ProjectDescription</p>
<h4>Open positions</h4>
@foreach (var missingPeople in Model.ProjectMissingPeople)
{
<label>@missingPeople.Text</label>
<button class="btn btn-project-join-small">JOIN</button>
}
</div>
Do you know how to help me?