80

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.

mdb
  • 52,000
  • 11
  • 64
  • 62
runxc1 Bret Ferrier
  • 8,096
  • 14
  • 61
  • 100

4 Answers4

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.

Community
  • 1
  • 1
JMP
  • 7,734
  • 6
  • 33
  • 34
  • 1
    what 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
  • 11
    Don't forget to add a reference to "System.Web.Extensions" for this to work – Levitikon Sep 14 '11 at 23:34
  • 1
    This 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
  • 1
    It's actually "Huckle Bearer", but I'll give you a +1 for the effort and movie. :) – Bryan Ray Aug 31 '12 at 03:22
  • 10
    The 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;"

1

Set property as internal. Depends on your structure, though. Take into consideration.

hakan
  • 3,284
  • 2
  • 19
  • 25