11

In my ASP.NET MVC4 application I have model that is defined like this:

public class Employee : BaseObject
{
    [JsonIgnore]
    public string FirstName { get; set; }
    [JsonIgnore]
    public string LastName { get; set; }
    [JsonIgnore]
    public string Manager { get; set; }

    public string Login { get; set; }
    ...
}

When I return this object using ApiController I get correct object without fields that have JsonIgnore attribute, but when I try adding same object inside cshtml file using below code I get all fields.

<script type="text/javascript">
    window.parameters = @Html.Raw(@Json.Encode(Model));
</script>

It looks like @Json.Encode is ignoring those attributes.
How can this be fixed?

1
  • Have you tried with the DataAnnotation [HiddenInput(DisplayValue = false)] Commented Jan 21, 2014 at 16:30

2 Answers 2

17

The System.Web.Helpers.Json class you used relies on the JavaScriptSerializer class of .NET.

The JsonIgnore properties you have used on your model are specific to the Newtonsoft Json.NET library used by default for ASP.NET Web API. That's why it doesn't work.

You could use the same JSON serializer in your Razor views for more consistency with your Web API:

<script type="text/javascript">
    window.parameters = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Works as expected. Thanks! :)
11

You can also use [ScriptIgnore] on your model i.e.:

public class Employee : BaseObject
{
    [ScriptIgnore]
    public string FirstName { get; set; }
    [ScriptIgnore]
    public string LastName { get; set; }
    [ScriptIgnore]
    public string Manager { get; set; }

    public string Login { get; set; }
    ...
}

And render as you were:

<script type="text/javascript">
    window.parameters = @Html.Raw(@Json.Encode(Model));
</script>

Comments

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.