embedding JSON data into the main template

I'm looking to include a JSON string by injecting some JavaScript on each page.

In the master page, I have:

public partial class TheMasterPage : System.Web.UI.MasterPage
{
  protected void Page_Init(object sender, EventArgs e)
    {
    if (Session["TheData"] == null) 
           {Session["TheData"] = GetData(DateTime.Today.Date); }
    }
}

This code checks if the session contains the necessary data for JSON serialization.

I want the data in the session to be added to the JavaScript of all pages.

In the aspx page, I have:

<asp:ContentPlaceHolder id="head" runat="server">
   <script type="text/javascript">
      var TheJsonData =... ;
   </script>
</asp:ContentPlaceHolder>

How can I inject the JSON data there? Which one will be executed first - the aspx injection or the Page_Init function?

For serialization, I use this code:

TheDataList = (List<MyModel>)Session["TheData"];

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new MyModel() });
String result = serializer.Serialize(TheDatatList);

I aim to $(document).ready(function () {ShowData(TheJsonData) }); with TheJsonData already loaded when the document ready event fires.

Thank you.

Answer №1

Consider using the following approach:

<script type="text/javascript">
    var jsonData = <%= new JavaScriptSerializer().Serialize(Session["Data"]) %>;
</script>

After implementing this, you should see a result similar to:

<script type="text/javascript">
    var jsonData = [{ property1: 'value1', property2: 'value2' }, { property1: 'value3', property2: 'value4' }];
</script>

The Page_Init function will execute before the view's code and will establish the session value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Troubleshooting a blank screen issue during JSON data retrieval on an Android device

I have a scenario where I am retrieving a large JSON response from a specific URL. The issue is that when the response is being fetched, the application displays a blank or black screen. To mitigate this problem, I would like to implement a ProgressDialog ...

Navigating a JSON object using jQuery

My current project involves sending a Json response to an Ajax function within my webpage. The structure of the Json response is as follows: {"one": 21, "two": 10, "three": 19, "four": 100} With this setup in place, I am now in the process of developing ...

Why is the else block being executed even though the condition in the if block is true in Javascript?

While delving into Node.js, I encountered an issue with my cartData.json file not updating properly. Here's the code snippet in question: routes.post("/cart", (req, res, next) => { let prodId = req.body.productId; let productList = []; let ca ...

After submitting the form, showcase the values in the textarea with each value on a new line for a

In my MVC, ASP.NET solution with angularjs integration, I have implemented a functionality where users can input values into a textarea and send them to a server. I am able to retrieve these values from the server and display them in the textarea using ng- ...

Updating Bootstrap Indicators with jQuery on Click Event

Unfortunately, I am unable to share an image due to limited internet data. My goal is to switch each image to its sprite equivalent. There are three list items that I'm struggling to change because they each have two classes that need to be updated. ...

Navigating through a nested JSON array and executing string manipulations in Java

My JSON array has the following structure: [ { "promise_detail": [ { "promise_date": "15 OCT 2020", "promise_amount": "USD 1086", "status": &quo ...

The iconbar feature in the mobile menu is experiencing functionality issues

I am currently experimenting with the iconbar property of mmenu (here: ) Unfortunately, I am encountering an issue. The menu opens as expected when I run the code. However, upon closing the menu, it first closes completely and then the container slides sl ...

Capture the current state of a page in Next.js

As I develop my Next.js application, I've encountered an architectural challenge. I'm looking to switch between routes while maintaining the state of each page so that I can return without losing any data. While initialProps might work for simple ...

Is there a way to trigger this pop-up after reaching a certain percentage of the page while scrolling?

I've been working on a WordPress site that features an "article box" which suggests another article to users after they scroll to a certain point on the page. However, the issue is that this point is not relative but absolute. This means that the box ...

Convert a collection of encoded JSON strings back into a readable format

The list of strings in the result object contains serialised JSON objects. This is an example of the serialised "result" : ["{\"Id\":\"91e02276\",\"Message\":\"Hi There\"}","{\"Id\":\"91e02277\" ...

Using RestSharp to convert a JSON string into an object

I have been struggling to deserialize the returned response.Content string without success. The WebApi action sends back a modified modelState with extra custom errors. On the MVC side, I attempted several methods but none of them were successful: JsonDe ...

Guide on exporting member formModule in angular

After compiling my code in cmd, an error message is displayed: ERROR in src/app/app.module.ts(3,10): error TS2305: Module '"C:/Users/Amir_JKO/my-first-app/node_modules/@angular/forms/forms"' does not have an exported member 'formModul ...

The conflict between Material UI's CSSBaseline and react-mentions is causing issues

Wondering why the CSSBaseline of Material UI is causing issues with the background color alignment of React-mentions and seeking a solution (https://www.npmjs.com/package/react-mentions) Check out this setup: https://codesandbox.io/s/frosty-wildflower-21w ...

What is the best way to choose all elements from an array based on their key and then combine their values?

Currently, I am working on an application that allows users to read articles and take quizzes. Each article is assigned to a unique category with its own _id. Quiz attempts are stored in a separate table that references the articles, which in turn referenc ...

Customize node.js response by overriding or adding another return statement

I have two variables, FirstName and LastName, that I need to include in the response data. It is important to note that the FirstName and LastName are not stored in the Student table. let result = await Student.get(id) let FirstName = "Paul" let LastName ...

Update the Slit Slider's effect to seamlessly fade in and out

I'm currently working on a website that requires a full-screen slider with fade-in and fade-out effects, complete with content and next/previous navigation options. After some research, I stumbled upon this solution. However, my main issue is figurin ...

Guide to positioning a THREE.js plane onto the exterior of a spherical object

Just starting out with Threejs and 3D graphics. I'm interested in learning how to position a plane of any dimensions on the surface of a sphere. Here's an example image of what I'm aiming for: example image ...

Eliminate a specific element from the dataset

My question revolves around a data array used to populate three drop down <select> boxes. How can I eliminate duplicate values within the drop downs without affecting the array itself? For example: data = { firstbox_a: ['grpA_1','gr ...

Encasing newly inserted child components within my designated slot

If I have a component with a single slot and instead of simply rendering all its children, I want to wrap each element individually, the following approach can be taken: Vue.component('MyElement', { render: function(createElement){ for (l ...

Adjust the Highcharts semi-pie design by eliminating the gap between the pie and the legend

I'm having trouble adjusting the spacing between the bottom of a semi circle donut chart in Highcharts and the legend below it. Despite my efforts, I have not been successful in reducing this gap. Here is the basic chart I am currently working on: h ...