当使用模型隐藏领域@ Json.En code [英] Hide field in model when using @Json.Encode

查看:74
本文介绍了当使用模型隐藏领域@ Json.En code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET应用程序MVC4我有一个这样的定义的模型:

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; }
    ...
}

当我使用ApiController返回这个对象,我得到正确的对象的没有字段有 JsonIgnore 属性,但是当我尝试添加里面CSHTML同一个对象使用下面code文件,我得到的所有字段。

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>

它看起来像@ Json.En code无视这些属性。

这怎么能解决吗?

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

推荐答案

您使用了 System.Web.Helpers.Json 类依赖于<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer%28v=vs.110%29.aspx\"><$c$c>JavaScriptSerializer .NET类的。

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

您已经在模型中使用的 JsonIgnore 属性是特定于默认情况下的ASP.NET Web API使用的Newtonsoft Json.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.

您可以与您的Web API使用相同的JSON序列在剃刀的意见更加一致:

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>

这篇关于当使用模型隐藏领域@ Json.En code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆