c# - 使用@Json.Encode 时隐藏模型中的字段

标签 c# asp.net asp.net-mvc json asp.net-mvc-4

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

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 返回此对象时,我得到正确的对象 without 字段具有 JsonIgnore 属性,但是当我尝试使用以下代码在 cshtml 文件中添加相同的对象时,我得到所有字段。

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

看起来 @Json.Encode 忽略了这些属性。
如何解决?

最佳答案

您使用的 System.Web.Helpers.Json 类依赖于 JavaScriptSerializer .NET 类。

您在模型中使用的 JsonIgnore 属性特定于默认用于 ASP.NET Web API 的 Newtonsoft Json.NET 库。这就是为什么它不起作用。

您可以在 Razor View 中使用相同的 JSON 序列化程序,以提高与 Web API 的一致性:

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

关于c# - 使用@Json.Encode 时隐藏模型中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21263436/

相关文章:

c# - 在页面加载时停止 JavaScript

c# - 为什么 C# ArrayList 没有 Resize 方法?

c# - 字符串连接追加每个元素文本

javascript - 使用 Html.BeginCollectionItem 帮助程序传递集合的分部 View

css - ASP.NET HTML 布局

c# - 带有 Blazor : Cannot figure out cookie authentification 的 ASP.NET Core

c# - 图像作为 GridView 中每列的标题

c# - asp.net 中的替代图像显示

asp.net-mvc - 如何在ASP MVC中返回JSON结构

asp.net - 如何只发送公钥来验证数字签名