3

Is there a way in MVC3 to set what properties the Json function outputs?

ie. properties on my model have an attribute that tells the Json function not to output them.

2 Answers 2

6

It looks like the ScriptIgnoreAttribute will do what you want. Just decorate whatever property you don't want serialized with it.

Sign up to request clarification or add additional context in comments.

Comments

1

Use anonymous method for that:

so instead of

return Json(it);

do

return Json(new {
  it.Name,
  CreatedAt = it.CreatedAt.ToString("D")
  // And so on...
});

this way you explicitly publish (map) set of attributes to the web which ensures that only allowed properties can be accessed from JSON.

If you don't want to Repeat Yourself, you can use JSON.NET serializer with which you can customise how objects are serialised. (So you can create custom HideAttribute and take that into account). With JSON.NET you will also need to write Controller.Json method replacement (SmartJson or so). But it should not be an issue I suppose.

2 Comments

hmmm, thats what I was afraid of. Was hoping I could just add an atribute and the Json function would be able to do it, like [HideJson]public string Password { get; set; }
You actually can do it with a bit of effort. Use JSON.NET - updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.