skip to Main Content

I’ve been trying to insert data from an SQL book details table into a JavaScript file using asp, my JavaScript file is linked at the end of my main aspx file, my SQL connection is working and I’ve been able to put it into JSON and checked it to make sure it all works(The database connection, the picking of items from the table and the JSON itself), however I’m struggling to find a way to export it to my Javascript file, I’m using:
Page.ClientScript.RegisterStartupScript(this.GetType(), "booksData", $"var booksData = {jsonBooks};", true);
Which I believe is supposed to make it possible for me to access it in my JS file however when I try to console.log(booksData); in the JavaScript file all I get is "booksData undefined" in my console.

This is the full aspx.cs file:

using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Web.Script.Serialization;
using static System.Net.Mime.MediaTypeNames;

namespace Porcupine.page_files.books_page
{
  public partial class books_page : System.Web.UI.Page
  {
    SqlConnection con = new SqlConnection("Placeholder");

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
      {

        List<Book> books = GetBooksFromDatabase();
        if (books.Count > 0)
        {
          Debug.WriteLine("Data retrieved successfully from the database.");
          
        }
        else
        {
          Debug.WriteLine("No data found in the database.");
        }

        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string jsonBooks = serializer.Serialize(books);
        Debug.WriteLine(jsonBooks);
        
        Page.ClientScript.RegisterStartupScript(this.GetType(), "booksData", $"var booksData = {jsonBooks};", true); 


      }
    }

    private List<Book> GetBooksFromDatabase()
    {
      List<Book> books = new List<Book>();

      try
      {
        con.Open();
        Debug.WriteLine("Database connection opened successfully.");
        SqlCommand cmd = new SqlCommand("SELECT title, author, publish, page_length, genre FROM books", con);

        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {

          Book book = new Book
          {
            Title = reader["title"].ToString(),
            Author = reader["author"].ToString(),
            PublishDate = reader["publish"].ToString(),
            PageLength = reader["page_length"].ToString(),
            Genre = reader["genre"].ToString()
          };
          books.Add(book);
        }
      }
      catch (Exception ex)
      {
        Debug.WriteLine("An error occurred: " + ex.Message);
      }
      finally
      {
        con.Close();
        Debug.WriteLine("Database connection closed.");
      }

      return books;
    }
  }

  public class Book
  {
    public string Title { get; set; }
    public string Author { get; set; }
    public string PublishDate { get; set; }
    public string PageLength { get; set; }
    public string Genre { get; set; }
  }
}

I was expecting the the code I wrote in the aspx.cs to create a booksData variable and load it with my ‘jsonBooks’ string, I’ve tried initializing the var bookData in the main aspx file inside but that obviously didn’t work as it just created a new variable without all the data I got in the aspx.cs file.

2

Answers


  1. Chosen as BEST ANSWER

    I couldn't make the RegisterStartupScript to work for some reason however I figured I could transfer the data by declaring the booksData globally in the aspx.cs file:

    protected string jsonBooks { get; set; }
    

    assigning it in the main aspx file in tags:

    <script>
      var booksData = <%= jsonBooks %>;
    </script>
    

    And accessing it in the separate JS file:

    console.log(booksData);
    

  2. May not be a real answer, but shows a working reproduced sample of original code:

    aspx :

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
            </div>
        </form>
    </body>
    <script src="SO77247462.js"></script>
    </html>
    

    aspx.cs :

    public class Book
    {
        public string Title;
        public string Author;
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<Book> books = GetBooksFromDatabase();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string jsonBooks = serializer.Serialize(books);
            Page.ClientScript.RegisterStartupScript(this.GetType(), "booksData", $"var booksData = {jsonBooks};", true);
        }
    }
    
    private List<Book> GetBooksFromDatabase()
    {
        List<Book> books = new List<Book>();
        for (int i = 1; i <= 5; i++)
        {
            books.Add(new Book() { Author = $"author {i}", Title = $"title {i}" });
        }
        return books;
    }
    

    Access data created in aspx.cs from included javascript file SO77247462.js :

    alert(JSON.stringify(booksData));
    

    result

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search