Interact with AngularJS and ASP.NET MVC by invoking controller actions

Previously, I used the following code to retrieve a JSON result from a function before integrating AngularJS:

$.ajax({
        url: '@Url.Action("getGamedata", "Home")',
        type: 'GET',
        dataType: 'json',
        cache: false,
        async: false,
        success: function (gameInfo) {
            //alert(gameInfo.Name); //Working OK
            for(var i=0;i<6;i++)
                createTable(gameInfo[i]);
        }
    });

The JSON result includes 6 items with details like name, genre, imageUrl, and more. With AngularJS in place now, I have a function that can dynamically build a grid:

function buildGridModel(tileTmpl) {
          var it, results = [];

          for (var j = 0; j < 6; j++) {

              it = angular.extend({}, tileTmpl);
              it.icon = it.icon + (j + 1);
              it.title = it.title + (j + 1);
              it.span = { row: 1, col: 1 };

              switch (j + 1) {
                  case 1:
                      it.background = "red";
                      break;

                  case 2: it.background = "green"; break;
                  case 3: it.background = "darkBlue"; break;
                  case 4:
                      it.background = "blue";
                      break;

                  case 5:
                      it.background = "yellow";
                      break;

                  case 6: it.background = "pink"; break;
              }

              results.push(it);
          }

          return results;
      }

In order to populate each tile in the grid with the corresponding title from the JSON data, I need to map them accordingly:

  1. 1st tile title = 1st JSON item title
  2. 2nd tile title = 2nd JSON item title
  3. and so on

Answer №1

Here is my solution: Implementing ajax within a function

function createGridModel(tileTemplate) {
          var element, gridValues = [];
          $.ajax({
              url: '/home/fetchGameData',
              type: 'GET',
              dataType: 'json',
              cache: false,
              async: false,
              success: function (gameData) {

                  for (var k = 0; k < 6; k++) {

                      element = angular.extend({}, tileTemplate);
                      element.icon = element.icon + (k + 1);
                      element.title = gameData[k]["Name"];
                      element.span = { row: 1, col: 1 };

                      switch (k + 1) {
                          case 1:
                              element.background = "red";
                              break;

                          case 2: 
                              element.background = "green"; 
                              break;
                          case 3: 
                              element.background = "darkBlue"; 
                              break;
                          case 4:
                              element.background = "blue";
                              break;

                          case 5:
                              element.background = "yellow";
                              break;

                          case 6: 
                              element.background = "pink"; 
                              break;
                          case 7: 
                              element.background = "darkBlue"; 
                              break;
                          case 8: 
                              element.background = "purple"; 
                              break;
                          case 9: 
                              element.background = "deepBlue"; 
                              break;
                          case 10: 
                              element.background = "lightPurple"; 
                              break;
                          case 11: 
                              element.background = "yellow"; 
                              break;
                      }

                      gridValues.push(element);
                  }
              }
          });

          return gridValues;
      }

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

The react-leaflet-heatmap-layer-v3 source directory could not be located

Upon attempting to utilize the npm package react-leaflet-heatmap-layer-v3 in my React TypeScript application, I successfully installed it and ran yarn start. However, I encountered the following warning messages: WARNING in ./node_modules/react-leaflet-hea ...

Discovering the Windows Identifier of the Opener Window in Chrome via JavaScript

I recently opened a link in a new window and realized that the current window's ID is now the ID of the newer window. I'm curious if there is any method to determine the window ID of the original window (the opener) from the perspective of the ne ...

A more concise method to verify if something is undefined in JavaScript

Anyone have suggestions for a more concise idiom to use? const x = module || window; // Reference Error fallback Is there a shorter method to verify the presence of module? ...

Which approach yields better performance: setting all dom events simultaneously, or incrementally?

Is it more effective to attach event listeners permanently or only when needed? For example, consider a scenario where you have a dropdown menu in your HTML that opens when clicked. Within this menu, there is a close button that closes the menu upon click ...

Exploring the power of intercepting response.send() and response.json() in express.js

Imagine having various instances where response.send(someData) is utilized. What if you wish to implement a universal interceptor that captures all .send functions and modifies someData? Is there a method within express.js to achieve this, such as hooks, ...

Send an object from AngularJS to an MVC controller and bind it to a corresponding class object

Trying to map an object from AngularJS to a custom C# class in an MVC controller, but encountering issues with the class object showing up as null. Here's the code snippet: $scope.Get = function () { var EService = [{ id: $scope.Id, ...

What seems to be the issue with this jQuery form submission?

I am currently working on a form that needs to be submitted using Ajax in order to avoid reloading the page. Although the Ajax call is reaching the server, it doesn't seem to trigger the necessary function. I have attempted both $.post and $.ajax, bu ...

Guidance on crafting a POST request for Google Cloud Messaging

I am currently utilizing Google Cloud Messaging to distribute messages to clients. However, I am looking to expand from sending messages to one recipient to multiple recipients at once. Outlined below is the basic structure of the request I am presently s ...

Encountering a "window not defined" error while implementing Leaflet in my Nuxt JS application

I'm encountering an issue while trying to generate my nuxt app, specifically on my 'Area' page. It seems like the error is related to the leaflet maps being used on this page. https://i.sstatic.net/Cj9ai.png Initially, I attempted to resol ...

Executing angularJS function when md-select is altered

I'm a beginner in angularJS and I'm looking to trigger a function after selecting an option in md-select. This is the code I have: <md-select ng-model="selectedSector" aria-label="select" onchange="filterCompanyList();"> <md-opt ...

Unable to update data from false to true in vue.js

What I'm trying to do is change the data from false to true in order to conditionally render a button when a payment has succeeded. When making an axios call, I receive 'succeeded' as the response in the JSON object and can log it to the con ...

Sending a function in React.js from one functional component to another

I'm facing an issue with my code where I have a function called postaviRutu in the App component that I need to pass to the child component Sidebar. When clicking on an element in Sidebar, I want it to call the postaviRutu function in App. I've a ...

Silent failure of product image upload in Java with Magento2 REST API leads to unexpected outcomes

Recently, I set up a Magento CE 2.1.2 online store. My main goal now is to utilize Java for uploading products to my store through the Magento REST API. After successfully configuring 2 leg OAuth using Apache-commons-httpclient and ensuring seamless produc ...

What is the cause of the redirection in htaccess even when the folder exists?

My .htaccess file includes the following code: Options +FollowSymLinks RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l RewriteRule .* index.php [L] AddType text/css .css I am e ...

Accessing data in JSON format from a URL

I'm working on a website that analyzes data from the game Overwatch. There's this link () that, when visited, displays text in JSON format. Is there a way to use JavaScript to read this data and display it nicely within a <p> tag on my si ...

How can I stop jQuery mobile from updating the document title?

It appears that jQuery mobile automatically uses the text content of data-role="header" to set the document.title. For example: <div data-position="fixed" data-role="header"> <h1>This text</h1> </div> To work around this, I ha ...

Utilize a jQuery selector to target the initial element of every alphabet character

I'm seeking some assistance with jQuery selectors and have a specific scenario that I need help with. Here is the HTML structure I am working with: <ul> <li class="ln-a"></li> <li class="ln-b"></li> <li cl ...

Stop jQuery function from activating twice during scrolling

I'm looking for a solution to optimize my code that detects if an element is in the viewport and triggers certain actions. Currently, it re-runs the code every time a scroll event occurs when the element is above the fold. Is there a way to make it on ...

Why is it that my JQuery sliders appear perfectly fine when viewed locally, but fail to show up when accessed on

I'm facing an issue with two JQuery sliders on my page. The local version works fine, but when I upload it to my web host, only one slider functions correctly. I need both of them to work as intended. Any insights on how to resolve this problem? See ...

Send data from a PHP form with various input types using JavaScript and AJAX

I need to submit a form with various fields, including multiples checkboxes selection and some hidden input fields via AJAX and then replace the HTML content with the response. I decided to use JavaScript/AJAX for this process, but did I make any mistakes? ...