Karan
Karan

Reputation: 15094

ASP .NET - JsonIgnore does not seem to work

Problem

I cannot serialize a object in MVC .Net when returning a json result because of loop references.

Self referencing loop detected for type ...

My entity class:

public class Subscriber
{
  [JsonIgnore]
  public virtual ICollection<Tag> Tags { get; set; }
}

In controller:

public JsonResult GetSubscribers(GridRequestModel model)
{
   data = ... get data ..
   JSON(data, JsonRequestBehavior.AllowGet);
}

It seems that the .NET serializer does not seem to take into account JsonIgnore since I still get the error.


Attempted Solution

I changed my controller to the following:

public JsonResult GetSubscribers(GridRequestModel model)
{
   data = ... get data ..
   JsonSerializerSettings jsSettings = new JsonSerializerSettings();
   jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

   string json = JsonConvert.SerializeObject(data, Formatting.None, jsSettings);

   JSON(json, JsonRequestBehavior.AllowGet);
}

This time I get:

The RelationshipManager object could not be serialized. This type of object cannot be serialized when the RelationshipManager belongs to an entity object that does not implement IEntityWithRelationships.

Also, not sure if I can return the string directly since I have return type of JsonResult. Would Json(json ... ) work?

Any help is appreciated. Thanks!

Upvotes: 2

Views: 2658

Answers (2)

Dmitry S.
Dmitry S.

Reputation: 8503

Unless you have overloaded the Json(..) methods in the controller, they are going to use .NET JavaScript serializer instead of JSON .NET.

Secondly, do not return EF class instances directly because they have different dependencies as well as possible lazy loaded associations. Map the data to the specifically designed view/json model classes instead.

Upvotes: 2

WeisserHund
WeisserHund

Reputation: 160

You can also use the [ScriptIgnore] attribute found in System.Web.Extensions

 public class SomeClass:Entity
{
    public SomeClass() { }
    public virtual int TestQuestionTypeValueId { get { return this.Id; } }
    [ScriptIgnore]
    public virtual TestQuestionTypes TestQuestionTypes { get; set; }
    public virtual string QuestionTypeValueText { get; set; }
    public virtual decimal QuestionTypeValue { get; set; }
}

Upvotes: 4

Related Questions