Mis*_*siu 10 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; }
...
}
Run Code Online (Sandbox Code Playgroud)
当我使用ApiController返回此对象时,我得到没有具有JsonIgnore属性的字段的正确对象,但是当我尝试使用下面的代码在cshtml文件中添加相同的对象时,我得到所有字段.
<script type="text/javascript">
window.parameters = @Html.Raw(@Json.Encode(Model));
</script>
Run Code Online (Sandbox Code Playgroud)
看起来@Json.Encode忽略了这些属性.
怎么解决这个问题?
Dar*_*rov 16
在System.Web.Helpers.Json您使用类依赖于JavaScriptSerializer类的.NET.
JsonIgnore您在模型上使用的属性特定于默认情况下用于ASP.NET Web API的Newtonsoft Json.NET库.这就是为什么它不起作用.
您可以在Razor视图中使用相同的JSON序列化程序,以便与Web API更加一致:
<script type="text/javascript">
window.parameters = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
</script>
Run Code Online (Sandbox Code Playgroud)
您也可以[ScriptIgnore]在您的模型上使用,即:
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; }
...
}
Run Code Online (Sandbox Code Playgroud)
并按原样渲染:
<script type="text/javascript">
window.parameters = @Html.Raw(@Json.Encode(Model));
</script>
Run Code Online (Sandbox Code Playgroud)