Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonIgnore not working in System.Web.Mvc.Controller

I have a web-API project and a simple class with a few properties, some are marked <JsonIgnore>.

In my MVC-controller I put Return Json(instanceOfMyClass, JsonRequestBehavior.AllowGet). All members are serialized. I put Return Json(Of MyClass)(instanceOfMyClass) in my WEBAPI-controller. Only the members I intend to serialize are present.

How can I ignore these properties independent of the controller that's going to serialize.

like image 578
Bernhard Döbler Avatar asked Aug 22 '15 20:08

Bernhard Döbler


1 Answers

The JsonResult in MVC does not actually use JSON.NET which is why [JsonIgnore] is not working. Instead it uses the JavaScriptSerializer class.

To make the JavaScriptSerializer skip a property, you can you the [ScriptIgnore] attribute on your model property.

An alternative would be to make a custom ActionResult that uses JSON.NET's JsonConvert to serialize the object which would then honor the [JsonIgnore] attribute.

like image 52
Mark Olsen Avatar answered Oct 04 '22 22:10

Mark Olsen