如何使用从ASP.NET MVC视图向JavaScript JSON传输JSON数据



我从控制器将数据序列化为JSON:

// Serialization
string jsonActivities = JsonSerializer.Serialize(ViewUserNotifications);
ModelData.JsonNotifications = jsonActivities;

视图:

@Model.JsonNotifications  
[{"Id":7,"UserSender":10,"UserReciever":4,"UserSenderName":"Maya","UserSenderSurname":"Robertson","UserSenderProfileImage":"88cf1027-eafd-493f-8b9c-add3f6812eb0_64.jpg","Message":"Maya is following you","Seen":true,"Created":"2021-09-04T21:07:50.3294555","Status":3}] 

我想知道如何将Json数据与Javascript一起使用?我试过这样:

<script>
var data = JSON.parse(@Model.JsonNotifications);
console.log(data);
</script>

然而,在控制台中,我得到了一个错误:

未捕获语法错误:需要的属性名称,得到的是"&">

如有任何帮助,我们将不胜感激!

解决问题:

var data = @Html.Raw(Model.JsonNotifications);

您不需要序列化数据。删除序列化代码

ModelData.Notifications = ViewUserNotifications;
var data = @Html.Raw(Json.Encode(@Model.Notifications));

以下是将JSON数据从ASP.NET传输到Java脚本的代码。

var result =  @Html.Raw(Model.JsonNotifications);
console.log(result);

最新更新