Does the Json.Encode() Helper use the JavaScriptSerializer class to encode a string to json?
I am getting a circular reference exception when using Json.Encode(Model) even though my class properties that are being serialized have the [ScriptIgnore] attribute.
My only guess is that maybe the Json.Encode() helper doesn't use the JavaScriptSerializer to serialize to json but I can't find the documentation anywhere on msdn.
@Html.Raw(Json.Encode(Model))
Here's an example of one of the models that has a property that should not be serialized...
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Script.Serialization;
namespace RobotDog.Entities {
    public class Character {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        [MaxLength(200)]
        public string Name { get; set; }
        public virtual Person Person { get; set; }
        [ScriptIgnore]
        public virtual Movie Movie { get; set; }
    }
}
                Does the Json.Encode() Helper use the JavaScriptSerializer class to encode a string to json?
Yes.
From the source code:
private static readonly JavaScriptSerializer _serializer = Json.CreateSerializer();
public static string Encode(object value)
{
  DynamicJsonArray dynamicJsonArray = value as DynamicJsonArray;
  if (dynamicJsonArray != null)
    return Json._serializer.Serialize((object) (object[]) dynamicJsonArray);
  else
    return Json._serializer.Serialize(value);
}
where JavaScriptSerializer is System.Web.Script.Serialization.JavaScriptSerializer
also to assist your issue see this thread
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With