Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide field in model when using @Json.Encode

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?

like image 717
Misiu Avatar asked Jan 21 '14 16:01

Misiu


2 Answers

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>
like image 68
Darin Dimitrov Avatar answered Nov 01 '22 22:11

Darin Dimitrov


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>
like image 44
hutchonoid Avatar answered Nov 01 '22 22:11

hutchonoid