Creating a lively JQ plot and saving it within an HTML file from a .aspx page using C# .net

I am currently in the process of developing a web-based application using Bootstrap.

My goal is to save a .aspx page as an HTML file within my application.

Upon writing the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;


 protected void btnExport_Click(object sender, EventArgs e)
    {

        string FileNamePath = @"D:\Test\Export.html";
        StreamWriter sWriter = File.CreateText(FileNamePath);

        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
  pnlData.RenderControl(htw);
        sWriter.WriteLine(sw.ToString());
  sWriter.Close();
    }

   <panel id="pnlData" runat="server">


<style type="text/css">

//given css here

</style>

 <div class="col-sm-12">
        <div class="col-sm-12">
            <!-- List starts -->
            <ul class="today-datas">
                <!-- List #1 -->
                <li class="bred" style="width: 350px;">
                    <!-- Graph -->
                    <div class="pull-left">
                        <span id="todayspark5" class="spark"></span>
                    </div>
                    <!-- Text -->
                    <div class="datas-text pull-right">
                        <span>98%</span>Compliance</div>
                    <div class="clearfix">
                    </div>
                </li>
                <li style="width: 350px;">
                    <!-- Graph -->
                    <div class="pull-left">
                        <i class="icon-group"></i>
                    </div>
                    <!-- Text -->
                    <div class="datas-text pull-right">
                        <span>Yes</span>Reviewed</div>
                    <div class="clearfix">
                    </div>
                </li>
                <li style="width: 350px;">
                    <!-- Graph -->
                    <div class="pull-left">
                        <i class="icon-laptop"></i>
                    </div>
                    <!-- Text -->
                    <div class="datas-text pull-right">
                        <span>20</span>Outstanding Count</div>
                    <div class="clearfix">
                    </div>
                </li>
  </ul>
        </div>
    </div>
<div class="col-sm-12">
        <div class="col-sm-6">
            <!-- Widget -->
            <div class="widget" id="DivHeader" runat="server">
                <!-- Widget head -->
                <div class="widget-head">
                    <div class="pull-left">
                        Compliance Chart</div>
                    <div class="widget-icons pull-right">
                        <a href="#" class="wminimize"><i class="icon-chevron-up"></i></a><a href="#" class="wclose">
                            <i class="icon-remove"></i></a>
                    </div>
                    <div class="clearfix">
                    </div>
                </div>
                <!-- Widget content -->
                <div class="widget-content">
                    <div class="padd" style="padding-bottom: 2px;">
                        <!-- Bar chart (Blue color). jQuery Flot plugin used. -->
                        <div id="curve-chart">
                        </div>
                    </div>
                    <div style="padding-bottom: 5px;">
                        <div class="legend" id="Legend" style="padding-left: 15px;">
                            <div class="header">
                                <span>Legend</span>
                            </div>
                            <table>
                                <tbody>
                                    <tr>
                                        <td>
                                            <span class="label bred"><i class="icon-2x icon-only"></i></span><span style="margin-left: 7px;">
                                                < 80% </span>
                                        </td>
                                        <td>
                                            <span style="margin-left: 20px;" class="label byellow"><i class="icon-2x icon-only">
                                            </i></span><span style="margin-left: 7px;">< 95% </span>
                                        </td>
                                        <td>
                                            <span style="margin-left: 20px;" class="label bgreen"><i class="icon-2x icon-only"></i>
                                            </span><span style="margin-left: 7px;">> 95% </span>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <!-- Widget ends -->
            </div>
        </div>
       </div>


 <script type="text/javascript">
            var chartResult = null;
            $(document).ready(function () { 
  var jsonurl = '/TestHandler/GetStatsData/Ajaxhandler.axd';
                $.ajax({
                    async: false,
                    url: jsonurl,
                    dataType: "json",
                    data: { AccId: 1 },
                    success: function (data) {
                        InitJQPlot(data);
                    }
                });
});

  function InitJQPlot(data) {                  
                var minValue = Math.round(Math.min.apply(Math, data.values)) - 1;
                var testData = [];
                var testLabel = [];
                var j = 0;
                for (var i = 0; i < data.Length; i++) {
                    testData.push([j, data.values[i]]);
                    testLabel.push([j, data.months[i]]);
                    j++;
                }
                var plot = $.plot($("#curve-chart"),
                   [{ data: testData, label: "Test Plot"}], {
                       series: {
                           lines: { show: true,
                               fill: true,
                               fillColor: {
                                   colors: [{
                                       opacity: 0.05
                                   }, {
                                       opacity: 0.01
                                   }]
                               }
                           },
                           points: { show: true }
                       },
                       grid: { hoverable: true, clickable: true, borderWidth: 0 },
                       yaxis: { min: minValue, max: 100 },
                       xaxis: {
                           ticks: testLabel
                       },
                       colors: ["#fa3031"]
                   });
}
</script>
</panel>
 <asp:Button ID="btnExport" OnClick="btnExport_Click" runat="server" Text="Export To HTML" />

The CSS has been enclosed within the <style> element. Additionally, I have included jquery.js,jquery-ui.min.js,jquery.flot.js,jquery.flot.resize.js,jquery.flot.pie.js, jquery.flot.stack.js,sparklines.js,sparkline-index.js

While I can see the dynamic chart on the .aspx page, it does not render properly in the HTML file. Instead, there is only a blank space inside the <div id="curve-chart">

I am experiencing difficulties generating the dynamic chart within the output HTML file.

If you have any insights or suggestions on how to successfully create the HTML file with the dynamic chart, your assistance would be greatly appreciated.

Answer №1

When you open the HTML file at D:\Test\Export.html, are you aware of where the graph data is being generated from? The link mentioned in the code snippet:

var jsonurl = '/TestHandler/GetStatsData/Ajaxhandler.axd';
relies on a relative path, assuming that the file is being run on a server where it can locate the required .axd file. However, if you are running it locally without an established server connection, there may be difficulties in fetching the data.

To mitigate this issue, consider changing the URL to an absolute path like

http://servername/TestHandler/GetStatsDAta/Ajaxhandler.axd
. This modification could potentially resolve the problem, although keep in mind that some browsers may flag this as a security risk when a local file tries to communicate with a remote server.

Answer №2

By globally declaring testData and testLabel, and assigning values from the page load using `JavaScriptSerializer', I am now able to generate an HTML file with a dynamic chart.

In the code behind file:

 public List<object> testDataList = new List<object>();
 public List<string> testLabelList = new List<string>();

 protected void Page_Load(object sender, EventArgs e)
 {
 //Load data into testDataList and testLabelList 
 }

 protected string JsontestDataArray
 {
    get
        {          
            var myArray = testDataList.ToArray();
            return new JavaScriptSerializer().Serialize(myArray);
        }
 }
 protected string JsontestLabelArray
 {
    get
        {
            var myArray = testLabelList.ToArray();
            return new JavaScriptSerializer().Serialize(myArray);
        }
 }

In the .aspx page:

$(document).ready(function () {    
            var testDataList = {values: <%= JsontestDataArray %>}; 
            for (var i = 0; i < testDataList.values.length; i++){                          
            testData.push([i, testDataList.values[i]]);         
            }        
            var testLabelList = {values: <%= JsontestLabelArray %>}; 
            for (var j = 0; j < testLabelList.values.length; j++){                          
            testLabel.push([j, testLabelList.values[j]]);         
            }          
});

With this setup, I can successfully load data for my dynamic chart.

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

Sending JSON data back to the server using KeyValuePair in C#

My goal is to send my JSON list back to the POST method (EditCompanyReportField) on the C# server side. The related parameter (fieldSorted) in my method is an array object, but the values are not being passed through. I have a few question marks regarding ...

Adapting npm scripts with Node.js based on the current context

Can you set up package.json to execute a different npm start script depending on the context? For instance, I want to run DEBUG=http nodemon app.js during development. However, I prefer to run node app.js in production. ...

Incorporating text overlays on images that are compatible with responsive websites is a top priority for me

This is a piece of HTML code that utilizes bootstrap 3 for design purposes. The challenge faced is related to positioning text over an image. When resizing the browser, the alignment of the text with the background gets disturbed. Assistance is needed in r ...

Using AngularJS to automatically include predefined data in an $http request

I am looking for a way to include a default data attribute in an http request. I came up with the following code: var app = angular.module('dumbhttp', []); app.service('dumbhttp', function ($http, $location) { this.post = function ...

Stopping the page from refreshing on an ajax call in asp.net: a guide

Is there a way to prevent page refresh during an Ajax call? I have multiple views that open when a user clicks on a link button from a tree view. Currently, the views are refreshing the page with each button click. I would like to display a loading image ...

Is my front-end JavaScript fetch request mistakenly being sent as a GET instead of a POST?

On clicking the submit button, a fetch request is triggered. Strangely, in the developer tools, it shows up as a GET request. I tested the request using Insomnia and it returned the handlebars site to me without any of my console logs appearing on either ...

"Learn the process of converting HTML content into a string in an Android application and then displaying

I utilized this/this to Print Receipts in part of POS(Point of Sale) from EPSON Printer Obtaining data Json from URL (within the Json Object is html print template): { "response": { "status": "<table>.... </table>" } } Hence, ...

Replacing variables in a function: A step-by-step guide

I have frequently used the replace function to eliminate classes in JavaScript. Currently, I am working on creating a JavaScript function that allows me to remove a specific class from an element by passing in the element and the class name. changeAddress ...

Sending JSON objects via AJAX to an ASP.NET callback page and serializing them

My webpage is built using asp.net and is fully ajaxified with the jquery library. I am encountering an issue where some users are experiencing an error when trying to serialize a JSON object. The error message reads: "There was an error deserializing the ...

Struggling with evenly positioning 6 elements in two rows using CSS

For positioning 6 different elements on a webpage, I've experimented with various methods: I initially tried stacking two unordered lists vertically but faced issues with scaling when stretching the page. Another attempt was using a table, but I stru ...

Utilizing JavaScript variables to generate a custom pie chart on Google

Greetings! I must admit that I am a novice, especially when it comes to JavaScript. My background is mainly in PHP. Recently, I came across a fantastic pie chart created by Google https://developers.google.com/chart/interactive/docs/gallery/piechart I a ...

Encountering a problem with GraphQL API fetching in Next.js: receiving the error message "React functionality 'useContext' is not supported in this environment."

Currently, I have developed a Next.js 14.2.3 application with a GraphQL API endpoint (which I replaced with localhost for StackOverflow). For data fetching, I am utilizing "@apollo/client": "^3.10.3" and "graphql": "^16.8.1". The product page path has been ...

Flexbox sets aside space for resized svg images

I am currently working on my site header and I want to implement flexbox for this purpose. I tried using justify-content: space-between; to evenly distribute the empty space between the divs. However, when I add an SVG image and scale it down to fit the ...

Spontaneous Link with JQuery and Colorbox

Just to clarify, I have no programming experience so please explain everything in simple terms. I am currently using a .js script within SharePoint and it's working perfectly! <!DOCTYPE html> <html> <head> <meta charset= ...

I am currently working with an input element that is set to hidden. I am trying to change its type to text using JavaScript, but I can't seem to figure out how to do it or if it is even possible

I'm stuck trying to change the type of an input element from hidden to text using JavaScript. I can't seem to figure out if it's even possible. Can someone please help me with this? Thanks! ...

In the strict mode tree, a reference named "grid" has been discovered

I encountered the following warning in the console: Warning: A string ref, "grid", has been found within a strict mode tree. String refs can potentially lead to bugs and should be avoided. It is recommended to use useRef() or createRef() instead. T ...

The max-width attribute is failing to apply to the form within the Bootstrap framework

login.html file: {% extends "base.html" %} {% block content %} <div class="container login-page-form"> <form id="login-form" action="/auth/login" method="post"> <div class="f ...

When attempting to convert large objects into JSON using JSON.stringify, a RangeError is thrown due to

Trying to convert a massive JavaScript Object into a string using JSON.stringify in my Node.js application. The objects are extremely large (tens of mega bytes) and do not contain any functions. I need to save the serialized objects to a file. However, I a ...

MUI AutoComplete does not currently support the type number with maxLength restriction. What steps can be taken to resolve this issue?

Hey there, I'm encountering an issue where maxLength is not working on the AutoComplete component when the input type is set to number. Any suggestions on how to resolve this? export default function Select({ onChangeInput, label, name, ...

retrieve PHP function calls as an array using Ajax

While working in PHP, I have encountered a situation where I needed to call a PHP function using AJAX: <button onclick="loop()">Do It</button> function loop() { $.get("ajax.php", { action: "true" }, function(result) { $("in ...