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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With