Storing data in JSON format and retrieving it using Javascript

My challenge involves plotting a chart using values from an object's list in my view with High Chart. However, I face the issue of accessing my model from JavaScript.

 public class MortgageCalculator
{
  public List<double> interest_month = new List<double>();

  public void calculations()
  {
    for(int i=1;i<=this.nPer;i++)
    {
        this.interest_month.Add(Math.Round(-Financial.IPmt((this.interest / 12) / 100, Convert.ToDouble(i), this.nPer, this.loan_amount),2));
    }
   }
}

In the Controller Code: I receive user input for calculations, update my model, and then redirect to the Results page where the chart of interest values should be displayed.

[HttpGet]
public ActionResult M_Calculator()
{
    var mortgageCalculator = new MortgageCalculator();
    return View(mortgageCalculator);
}

[HttpPost]
public ActionResult M_Calculator(MortgageCalculator mortgageCalculator)
{    
    UpdateModel(mortgageCalculator);

    //call calculation functions here
    mortgageCalculator.Amortization();

    return View("Results",mortgageCalculator);
}

In the View Code:

@model Calculators.Models.MortgageCalculator
@{
  ViewBag.Title = "Results";
}


@Scripts.Render("~/Scripts/lineChart.js")\

<div id="container" style="min-width:310px; height:400px; margin:0 auto">
    @section scripts
    {
        <script src="~/Scripts/highcharts.js"></script>
        <script src="~/Scripts/highcharts.src.js"></script>
        <script src="~/Scripts/lineChart.js"></script>
    }

</div>

I am seeking guidance on how to access the list from the model in my lineChart.js JavaScript file to plot the chart. It seems like I may need to use JSON, but I'm uncertain about how to proceed. Any assistance would be greatly appreciated.

Thank you

Answer №1

If you want to achieve this task, there are two methods you can follow. The first option is to utilize jQuery to fetch the JSON object and modify your Action to return a JsonResult (which I personally find easier). Alternatively, you can generate the JavaScript object by constructing the string using C#.

1. Utilizing jQuery to obtain the JSON object

Adjust your Action to return Json instead of a View.

public ActionResult M_Calculator()
{
    var mortgageCalculator = new MortgageCalculator();
    mortgageCalculator.calculations();
    return Json(mortgageCalculator.interest_month); // only return the array
}

In your View, you can retrieve the JSON object using jQuery as shown below.

<script type="text/javascript">
    var calcURL = '@Url.Action("M_Calculator", "MyController")';
    var interestMonthsArray = [];
    $.getJSON(calcURL, function (data) {
         interestMonthsArray = data;
    });
</script>

2. Using C# to construct the JSON object

In your View:

@model Calculators.Models.MortgageCalculator
@{
  ViewBag.Title = "Results";
  bool first = true;
  string arrStr = "[";
  foreach (var month in Model.interest_month)
  {
     if (first)
     {
       first = false; 
     }
     else
     {
        arrStr += ",";
     }
     arrStr += month;
  }
  arrStr += "]";
}
....
<script type="text/javascript">
   var interestMonthsArray = @arrStr;
</script>

You also have the option to create this string in your Action method or even within your model class.

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

Having trouble aligning my slider in the center

Despite trying various methods to center this slider, such as using align="center" and different margin styles on the images and slider div itself, I am still facing alignment issues. Any assistance would be greatly appreciated. This is my first time posti ...

"Encountering issues with Node.js while loading required modules

Having created an API utilizing hummus.js, I encountered a problem after uploading it to my server (Ubuntu Root + Plesk Onyx) and performing an npm install on my package.json. Despite receiving a "Success" status message during the installation process, my ...

Creating a Three-Dimensional Bounding Box in THREE.js

After successfully utilizing the OBB.js in three.js examples to fetch the center, halfSize, and rotation values, the next step is to determine how to calculate the 8 corners of the bounding box based on this information. Additionally, we need to understa ...

I'm encountering an error while attempting to parse the XML file

Need help with ajax call $j.ajax({ url: "http://www.earthtools.org/timezone/40.71417/-74.00639", dataType: "jsonp", complete: function(data){ console.log(data); } }); The URL returns XML, but I'm trying to use JSONP to avoid cross-site s ...

Alter the configuration of a JSON object

I'm currently working on modifying the following JSON text. It has the structure as shown below: { "cabecera": { "tipo_cambio": "", "fecha_emision": "", "total": "" }, "detalle": { "940b130369614bd6b687dc5b41623439": { " ...

Use jQuery to display the user input value in real-time

I am in the process of developing a dynamic calculation program to sharpen my jQuery skills, but unfortunately, I'm facing some challenges. I have managed to store values in variables as shown in the code snippet below. <form> Table of: ...

Three-dimensional.js and components of the design

Looking for advice on how to manipulate individual parts of a 3D model in Three.js. My model is made up of various components that I need to control separately. Any tips or suggestions would be greatly appreciated. Thank you! ...

Is it possible to filter JavaScript Array while ensuring that select options do not contain duplicate IDs?

I am utilizing two datatables with drag and drop functionality. Each row in the datatables contains IDs. When I drag a row from table 1 to table 2, the data is stored in an Array. I have an addArray function that pushes the IDs into the Array, filters out ...

What is the process for incorporating a shared variable into a JSON-based Selenium builder testing suite?

How can I include a variable like ${url} in each test? In the JSON code for a single test, it looks like this: "data": { "configs": { "manual": { "url": "https://my_url" } }, "source": "manual" }, I would like to hav ...

The backend response was "<Response [502]>" along with an error message stating that string indices must be integers

Currently, my goal is to initiate a REST request towards the specified end-point. import requests param1 = "abc" param2 = "def" input_data = """{{"param1": {}, "param2": {}}}""".format ...

What is the best way to transform a JSON array in text format into a JSON object array using NodeJS or JavaScript?

I have a RESTful API built with Node.JS and ExpressJS. I want to retrieve a JSON array from the FrontEnd and pass it into my API. api.post('/save_pg13_app_list', function (req, res) { var app_list = { list_object: req.body.li ...

Creating dynamic JSON endpoints using JSP with Spring MVC

When working with JSON in my webapp, I have successfully passed a variable wordId to the Spring-mvc Controller using a static URL. However, I am unsure of the best practice for dealing with dynamic or parametric URLs. Controller Section: @RequestMapping( ...

Navigating a complex web: Djikstra algorithm applied to a multigraph

Encountering an issue while implementing Dijkstra's algorithm on a multigraph. The graph consists of nodes representing stops with information and connections to other stops (edges). However, the challenge arises when there are multiple bus options be ...

What causes the difference in behavior of nodejs function arguments when explicitly called?

As I refactor my nodejs application to improve code readability, I encountered an issue when calling a function directly. The following code works perfectly: router.route('/').get(({ query }, res, next) => { ItemsLogic.getItems(query) .the ...

Arrange the object's key-value pairs in ng-repeat by their values

I'm completely new to AngularJS and I am working with an API that returns key-value pairs related to different sports. $scope.sports = { 1: "Soccer", 2: "Tennis", 3: "Basketball" ... }; My challenge is sorting these items by sport name: <ul> ...

I am looking for a solution to transform JSON data into XML format using node.js

I'm looking to convert JSON data on my node.js server into an RSS feed. Can anyone recommend the most efficient method for accomplishing this task? Additionally, once the conversion is complete, I will need the RSS file to be outputted or overwritten. ...

Is it possible to establish communication between JAVA and Javascript using Sockets?

Recently, I developed a Java application that generates some data and saves it in a text file on my computer. Instead of saving this data in a text file, I am looking to send it via Socket. Here is an example: Java public static void main(String argv[] ...

What is the reason for the incompatibility between Bootstrap and Vanilla JavaScript?

Why does my slideshow crash when I use Bootstrap with vanilla JavaScript? It seems like there is a timeout or something... I'm not sure why this is happening. When I remove Bootstrap, the slideshow works fine. Here is my code: I attempted to remove ...

Decoding JSON objects in Python continues to reveal their underlying structure

Experimenting with the Telegram bot API, I've been attempting to translate JSON objects into an array, but no matter what method I use, I keep receiving the JSON format... import urllib.request import json #Insert your Authentication token here tok ...

Within a single component, there are various types present when looping through an array containing objects

Hey there, I'm looking to iterate through an array containing objects with different types within a single component. operations = [ { "id": 15525205, "type": "mise_en_prep", & ...