I have a POCO class that is being sent to the browser as a JSON string in .NET 3.5 sp1. I am just using the default JSON serialization and I have some fields that I want to ignore. I want to put an attribute similar to [System.Xml.Serialization.XmlIgnore] on them so that they are not serialized.
Asked
Active
Viewed 4.7k times
4 Answers
121
I use the ScriptIgnore attribute on my model like so:
public class Item
{
[ScriptIgnore]
public Item ParentItem { get; set; }
}
In this particular scenario I was getting a circular reference error from the Json serializer, so I simply ignored it. I was asking a similar question here on SO when I was turned on to the difference between a Model and ViewModel.
-
1what if its not POCO but a generated EntityModel, I do not want to edit the generated code, is there a workaround to add ScriptIgnore attribute to the generated entity model. – hazimdikenli Nov 11 '10 at 10:09
-
@hazimdikenli you might have to utilize partial class for this. – Anand Aug 05 '11 at 16:18
-
11Don't forget to add a reference to "System.Web.Extensions" for this to work – Levitikon Sep 14 '11 at 23:34
-
1This helped me stop my toJson(Model) bringing back some unwanted fields,, but ideally with an API, you will need to make an new Area, with a New Model and controller to avoid cross annotations.. but im too lazy. Thanks +1 – Piotr Kula Jan 26 '12 at 16:35
27
[ScriptIgnore]
is your huckaberry.

Andrew Whitaker
- 124,656
- 32
- 289
- 307

Wyatt Barnett
- 15,573
- 3
- 34
- 53
-
1It's actually "Huckle Bearer", but I'll give you a +1 for the effort and movie. :) – Bryan Ray Aug 31 '12 at 03:22
-
10The original answer is correct, he says "huckleberry", not "huckle bearer". http://www.imsdb.com/scripts/Tombstone.html – heisenberg Apr 22 '13 at 18:24
-
7...as in "Huckleberry Finn" - a reference to the quintessential "every man", who instinctively strives to "do the right thing" - a true friend you can always count on...hence "I'm your Huckleberry", meaning "you can count on me". – John Holliday Sep 25 '13 at 19:51
2
You just need to add the
[ScriptIgnore(ApplyToOverrides = true)]
into your text template (.tt) file.
Here a portion of my text template before
#>
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
<#
Once I inserted the code the line above the codeStringGenerator
my classes auto generated and looked like this:
[ScriptIgnore(ApplyToOverrides = true)]
public virtual ICollection<Currency> Currencies { get; set; }
I also needed to modify the UsingDirectives
function to insert "using System.Web.Script.Serialization;"

Alex Boutin Flegel
- 92
- 5
-
`ApplyToOverrides` seems to be very important on a virtual property – Kind Contributor Sep 13 '16 at 04:08
1
Set property as internal. Depends on your structure, though. Take into consideration.

hakan
- 3,284
- 2
- 19
- 25