I am trying to fetch a complex ViewModel object to my view, via JQuery $.getJSON
. However, although it works for simple objects, when my viewmodel contains other object lists as part of it, my Ajax request stops working.
This is how I fetch the data,
$.getJSON('/Company/GetCompanies', function(data) {
viewModel.model = ko.mapping.fromJS(data)
ko.applyBindings(viewModel)
});
This is working viewmodel,
public class CompanyIndex
{
public IList<CompanyWithDetail> Companies { get; set; }
public void FillCompanies()
{
UnitOfWork unitOfWork = new UnitOfWork();
unitOfWork.CompanyRepository.SetProxy(false);
var CompanyFromDB = unitOfWork.CompanyRepository.GetCompanyWithDetails();
Companies = new List<CompanyWithDetail>();
foreach (Company company in CompanyFromDB)
{
CompanyWithDetail newCompany = new CompanyWithDetail();
newCompany.CompanyName = company.CompanyName;
Companies.Add(newCompany);
}
unitOfWork.Dispose();
}
}
This is the CompanWithDetail class,
// For sake of demonstration it only contains name
public class CompanyWithDetail
{
public string CompanyName { get; set; }
}
This is working fine. However, when I add
public IList<CompanyFaxNumber> FaxNumber { get; set; }
this property to CompanyWithDetail class, and fill it in FillCompanies()
method of CompanyIndex
viewmodel, my ajax get request stops working.
This is my controller btw, in both cases it returns the correct data, but jquery $.getJSON
does not receive when I add complex objects.
public ActionResult GetCompanies()
{
var model = new CompanyIndex();
model.FillCompanies();
return Json(model ,JsonRequestBehavior.AllowGet);
}
EDIT 1:
By saying getJSON does not receive the data, I mean the body of function is not executed.
$.getJSON('/Company/GetCompanies', function(data) {
alert('test')
});
For instance, alert is working when there is no complex object but it stops working when I add objects to viewmodel.
EDIT 2
This is the error when I call 'Company/GetCompanies' from browser instead of ajax.
A circular reference was detected while serializing an object of type 'CompanyManagement.Models.CompanyEmail'.
Do i need to do something special to pass complex objects from controller to view ? Any ideas?