6

in asp web api i have this controller that respond to ajax request and send back json data:

public IEnumerable<PersonaleDTO> GetPersonale()
{
    var n = (from p in db.Personale
             select new PersonaleDTO { Id = p.Id, Nome = p.Nome, Cognome = p.Cognome Cellulare = p.Cellulare, Email = p.Email, Attivo = (bool)p.Attivo }).ToList();
    return n;
}

This method return seven object and it's correct.

Now when i receive back the data in the json format i see that i receive also and $id member along with the id, Nome, Cognome...

What is the $id variable? How can remove this from the json response?

Tom
  • 4,007
  • 24
  • 69
  • 105

1 Answers1

10

Try this code in WebApiConfig

var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;

Edit : If for some reason you're using a custom ContractResolver then as per this post

The custom ContractResolver setting overrides the PreserveReferencesHandling setting.

In your implementation of DefaultContractResolver/IContractResolver, add this;

public override JsonContract ResolveContract(Type type) {
    var contract = base.ResolveContract(type);
    contract.IsReference = false;
    return contract;
}

This behaves similarly to the PreserveReferencesHandling.None setting without a custom ContractResolver.

Community
  • 1
  • 1
Nilesh Gajare
  • 6,302
  • 3
  • 42
  • 73