Cannot load JSON file from Visual Studio 2013

I am currently working on building a drag-able network diagram using d3.js, and I've come across an unusual issue. Whenever I try to run the page from Visual Studios 2013, I encounter the following error:

"Unhandled exception at line 25, column 13 in http://localhost:58771/HtmlPage1.html

0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'links': object is null or undefined"

However, when I move both the HTML page and the .json file to my local drive, the page opens without any issues.

Below is a snippet of the d3 code that is causing the problem:

     d3.json("graph.json", function (error, graph) {
        graph.links.forEach(function (d) {
            d.source = graph.nodes[d.source];
            d.target = graph.nodes[d.target];
        });

The json file is too large to be included here. My main question is why does it work when accessed from my local drive, but not when within the ASP project in Visual Studio. The network diagram will be part of an ASP.net application, so changing the website's format is not an option.

Any assistance with this issue would be greatly appreciated. Thank you.

Answer №1

When running the ASP.NET project on IIS Web Server, it may encounter issues with Windows directories. To resolve this, ensure that the d3.json() URL property matches the location of the json file URL. Since the project is running on a virtual server, follow these steps:

  1. Include the following code within the web.config file's

    <configuration></configuration>
    tag to allow IIS to serve the json file. Without this code, IIS may consider the json file as a part of the URL path:

    <system.webServer>
     <handlers>
       <remove name="BlockViewHandler"/>
       <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
       </handlers>
        <staticContent>
         <mimeMap fileExtension=".json" mimeType="application/json" />
        </staticContent>
        </system.webServer>
    
  2. Obtain the URL of the json file and provide it to the d3.json() function.

    If you are using the Razor View Engine, retrieve the URL as follows:

    'I recommend storing graph.json within a folder named Data'

     var url = "@Url.Content("~/Data/graph.json")";
     d3.json(url, function (error, graph) {
           graph.links.forEach(function (d) {
            d.source = graph.nodes[d.source];
            d.target = graph.nodes[d.target];
        });
    

    If you are using ASP.NET Webforms, adjust the d3.json() function:

       d3.json("~/Data/graph.json", function (error, graph) {
           graph.links.forEach(function (d) {
            d.source = graph.nodes[d.source];
            d.target = graph.nodes[d.target];
           });
    

    Navigate through the solution explorer to locate the graph.json file and save it as if it were in a Windows directory. I typically use ~ to eliminate the path and start from the top.

Hope this guidance proves useful.

Answer №2

Here is the complete code for your review:

!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://d3js.org/d3.v2.js"></script>
<style>
    .link {
        stroke: #ccc;
    }

    .nodetext {
        pointer-events: none;
        font: 10px sans-serif;
    }
</style>
</head>
<body>
<script type="text/javascript">

    var w = 1280,
        h = 1024;

    var color = d3.scale.category20();

    var vis = d3.select("body").append("svg:svg")
        .attr("width", w)
        .attr("height", h);

    d3.json("graph3-copy.json", function (json) {
        var force = self.force = d3.layout.force()
            .nodes(json.nodes)
            .links(json.links)
            .gravity(.05)
            .distance(100)
            .charge(-100)
            .size([w, h])
            .start();

        var link = vis.selectAll("line.link")
            .data(json.links)
            .enter().append("svg:line")
            .attr("class", "link")
           .attr("x1", function (d) { return d.source.x; })
           .attr("y1", function (d) { return d.source.y; })
           .attr("x2", function (d) { return d.target.x; })
           .attr("y2", function (d) { return d.target.y; });

        var node_drag = d3.behavior.drag()
            .on("dragstart", dragstart)
            .on("drag", dragmove)
            .on("dragend", dragend);

        function dragstart(d, i) {
        force.stop() // stops the force auto positioning before you  start dragging
        }

        function dragmove(d, i) {
            d.px += d3.event.dx;
            d.py += d3.event.dy;
            d.x += d3.event.dx;
            d.y += d3.event.dy;
            tick(); // this is the key to make it work together with updating both px,py,x,y on d !
        }

        function dragend(d, i) {
            d.fixed = true; // of course set the node to fixed so the force doesn't include the node in its auto positioning stuff
            tick();
            force.resume();
        }

        var node = vis.selectAll("g.node")
            .data(json.nodes)
          .enter().append("svg:g")
            .attr("class", "node")
            .call(node_drag);

        node.append("svg:image")
            .attr("class", "circle")
            .attr("xlink:href", "https://github.com/favicon.ico")
            .attr("x", "-8px")
            .attr("y", "-8px")
            .attr("width", "16px")
            .attr("height", "16px");

        node.append("svg:text")
            .attr("class", "nodetext")
            .attr("dx", 12)
            .attr("dy", ".35em")
            .text(function (d) { return d.name });

        force.on("tick", tick);

        function tick() {
            link.attr("x1", function (d) { return d.source.x; })
                .attr("y1", function (d) { return d.source.y; })
                .attr("x2", function (d) { return d.target.x; })
                .attr("y2", function (d) { return d.target.y; });

            node.attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });
        };


    });

</script>
</body>
</html>

The error message in Firefox console suggesting the JSON file is empty seems incorrect. I have verified that the data is present and the webpage runs properly outside of Visual Studio environment.

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

Tips for resizing a Textbox by dragging in asp.net?

Is there a way to dynamically adjust the size of a Textbox by dragging it in an ASP.NET application during run-time? ...

Ensuring the correctness of phone numbers by validating them with country codes through the use of

I'm currently working on validating phone numbers using intl-tel-input, following the example provided at Below is the code snippet I've been using: var telInput = $("#phone"), errorMsg = $("#error-msg"), validMsg = $("#valid-msg"); // initial ...

The send_keys() function in Selenium version 3.141.0 works perfectly on Windows, but unfortunately, it is not functioning correctly on Linux Debian 11

I've been experimenting with web automation using Selenium. Everything was running smoothly until I updated my packages - now the send_keys() method isn't functioning on Linux, but it's working fine on Windows with the same versions. I&apo ...

Angular binding causing decimal inaccuracies

Within my $scope, I have a variable tobing that can be either 2.00 or 2.20, and I am binding it to: <span>{{datasource.tobind}}</span> I want the displayed text to always show "2.00" or "2.20" with the two last digits, but Angular seems to au ...

Tips for transferring data from one asynchronous function to another in AngularJS

How to transfer a global variable value between two Angular functions? Here are the two global variables: $scope.genewtId = null; $scope.data1 = null; The two Angular functions in question are: $scope.getID = function() { Service1.getId("abc").then(f ...

What are the steps to utilizing the $document service in AngularJS?

I am a complete beginner when it comes to AngularJS and JavaScript in general, and I find myself a bit confused about the usage of $document. From what I understand, $document provides access to some JQuery functions. So, if I want to remove an element tha ...

Verifying that a parameter is sent to a function triggering an event in VueJS

One of the components in my codebase is designed to render buttons based on an array of objects as a prop. When these buttons are clicked, an object with specific values is passed to the event handler. Here's an example of how the object looks: { boxe ...

Issue: Unhandled ReferenceError - onChangeAssignedGroup function is not declared within scope at HTMLSelectElement.onchange

Having difficulty calling a PHP script via JavaScript when the user changes the value in the "Assigned To Group" selection. The goal is to modify the option list of a yet-to-be-created "Assign to User" selection. An error message pops up stating that it d ...

What is the relationship between $.when, apply(), and $.done() within the scope of this function?

I recently received this function from a helpful SO user that allows for returning a variable number of jQuery $.get() requests. The initial part seems pretty straightforward, but I am struggling to understand how $.when(), apply(), and $.done() are inte ...

Dealing with Memory Issues in Google Apps Scripts

Currently, I am addressing a challenge within my organization that requires me to maintain some level of ambiguity. However, I have been granted permission to discuss this issue openly. The task at hand involves creating a script to analyze a Google Sheet ...

Execute a function for each template or controller when the page loads

I recently developed a function for my application that verifies the users' information. I implemented this in my authentication controller within the $rootScope. However, I am facing an issue where I need to manually invoke this function in all of m ...

Maintaining accurate type-hinting with Typescript's external modules

Before I ask my question, I want to mention that I am utilizing Intellij IDEA. In reference to this inquiry: How do you prevent naming conflicts when external typescript modules do not have a module name? Imagine I have two Rectangle classes in different ...

Is it possible to examine my API request URL from the API's perspective using a Linux Command Line Utility?

Curious to uncover the request URL I'm sending to a JSON API, as I suspect my URL parameters might be getting removed by a proxy server. How can I verify this information? Is there a method to view the request URI using tools like cURL, WGET, or any o ...

Symfony JSON responses with the field name included in the output

Currently, I am attempting to retrieve a value from my database under the 'action' field. It is stored as a JSON string but for now, I have it saved as a single value like this: 'command'=>'get','target'=>&apo ...

Updating the object in router.get and res.render in Node.js and Express after loading

When loading the page, I encounter an error with req.body.firstname.length inside router.use. The error states: TypeError: Cannot read property 'length' of undefined The issue arises because the default value is undefined for the input form. ...

What is the process of combining a JSON bundle with a Jade template?

As a newcomer to this workflow, I have an Express app set up with Jade as the template engine. My current challenge involves using "gulp-bundle-assets" to bundle all scripts into one file with a hashed name for caching purposes. Additionally, it generates ...

Tips for automatically updating a MaterialUI DataGrid in a React JS application

Here's an overview of my current project: Users can save rows from deletion by clicking checkboxes (multiple rows at a time). Any unchecked records are deleted when the user hits the "purge records" button. I received some guidance on how to achieve ...

What is the Next.js equivalent of routing with rendering capability for nested component paths?

I am new to Next.js and so far have been loving the experience. I'm a bit stuck on how to achieve the equivalent of the following code in Next.js These are all client-side routes that render nested components on the user page. The value of ${currentP ...

reverting the effects of a javascript animation

I am expanding the size of a carousel on a specific pane by adjusting its height and position. Here is how I achieve this: if(currentPane==2) { $("#carousel").animate({height:320},1000); $("#carousel").animate({top:411},1000); $("#dropShadow") ...

VueJS, when used in conjunction with Vuetify, might require an extra loader to handle scoped css

While attempting to compile my VueJS code using webpack, I encountered an error with the following code: <template> <v-app-bar app color="blue" flat height="100px"> <v-img class="mx-2" contain max-height="80" m ...