0

How can I prevent the "Self-referencing loop detected" error while serialising the object in MVC View ?

 var fieldDependants = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model);

I added following configuration snip in Global.asax But still getting the same error.

config.Formatters.JsonFormatter
            .SerializerSettings
            .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Thanks

dush88c
  • 1,918
  • 1
  • 27
  • 34
  • where in global.asax did you add this default. You can also pass this value to the `serializeobject` call itself. – Steve0 Jun 20 '17 at 18:43
  • Your second code snippet configures the serializer used by MVC. Your first code snippet does not use that serializer. –  Jun 20 '17 at 19:30
  • You might have a look at my answer on **[“Self Referencing Loop Detected” exception with JSON.Net](https://stackoverflow.com/questions/40472419/self-referencing-loop-detected-exception-with-json-net/51235783#51235783)** page. – Murat Yıldız Jul 08 '18 at 20:40

2 Answers2

1

Not knowing where you placed the default in Global.asax you can ensure the setting is what you want by setting it explicitly with the SerializeObject call

Newtonsoft.Json.JsonConvert.SerializeObject(model, New Newtonsoft.Json.JsonSerializerSettings With {.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore})  //VB


Newtonsoft.Json.JsonConvert.SerializeObject(model, New Newtonsoft.Json.JsonSerializerSettings() {ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore})  //CS
Steve0
  • 2,233
  • 2
  • 13
  • 22
0

The JsonFormatter.SerializerSettings are only used by Web API. They will not be picked up by a direct call to SerializeObject from an MVC view. You could try setting the global DefaultSettings delegate on JsonConvert:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};

If that doesn't work, you will need to pass the settings to SerializeObject directly as shown by @Steve in his answer.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300