skip to Main Content

I serialized my data to JSON from the controller:

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

View:

@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}] 

I wonder how can I use this Json data with Javascript? I tried like this:

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

However, in the console I got an error:

Uncaught SyntaxError: expected property name, got ‘&’

Any help is appreciated!

Problem solved:

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

2

Answers


  1. you don’t need to serialize data. remove the serialization code

    ModelData.Notifications = ViewUserNotifications;
    
    var data = @Html.Raw(Json.Encode(@Model.Notifications));
    
    Login or Signup to reply.
  2. Here are the code to transfer the JSON data from the ASP.NET to a Java script.

     var result =  @Html.Raw(Model.JsonNotifications);
     console.log(result);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search