在我的 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/