I’m using a WCF Service in which I would like to respond with a list of objects. As my objects are generated by entity framework, I can’t really return a List as it has some circular references and default serialization fails. Thus, I’m using anonymous types to create a list of objects containing only the properties I need.
This is what I’m doing, using Json.NET:
[OperationContract]
public string DoWork()
{
using (X ent = new X())
{
var modules = from p in ent.Modules select new { Name = p.Name, Value = p.ID };
return JsonConvert.SerializeObject(modules);
}
}
Now this is my javascript which renders the result inside a table:
function btn_onclick() {
var srv = new DDSProjectManagement.ProjectsService();
srv.DoWork(Res, null, null);
}
function Res(dataList) {
var divObj = document.getElementById('tablePos');
var name = 'Name';
var desc = 'Description';
var tableStart = '<table><tbody><tr><th>Name</th><th>Description</th></tr>';
var tableContent = '';
var tableEnd = '</tbody></table>';
for (var i = 0; i < dataList.length; i++) {
tableContent += '<tr><td>' + dataList[i].Name + '</td><td>' + dataList[i].Value + '</td></tr>';
}
divObj.innerHTML = tableStart + tableContent + tableEnd;
}
If I do this, the parameter javascript gets is just a string and it is not able to see it as a list of my objects. Of course, it should be a Json string and I could try to parse it such that it extracts the objects from it. But I really want to use the javascript as it is now and modify the service. For example, changing my service in the following will work just fine:
public List<SimpleObject> DoWork()
{
return new List<SimpleObject>() { new SimpleObject("Florin", 1), new SimpleObject("Andrei", 2) };
}
SimpleObject is not an EntityFramework object so this has no problem. I suppose the default serializer is a Json one and javascript should get basically the same parameter: a Json string.
So my question is how do i make my method send a list of anonymous type objects to my JS as building the string via Json.NET didn’t work?
Thanks in advance.
This finally worked for me. The return type of the method is Stream and here is how it works: