What is the process of transferring a parameter from an ActionResult to a JsonResult?

Is it possible to successfully pass the Id parameter from ActionResult to JsonResult? I am currently experiencing difficulties with passing the Id data to the JsonResult parameter, resulting in an error when trying to execute the following code.

I am utilizing angularjs to showcase a list of tables.

[HttpGet]
public ActionResult ManageCustomerStocks(Int64 Id)
{
    return View();
}

public JsonResult GetStocksByCustomerId(Int64 Id)
{
   List<CustomerStocksVM> model = new List<CustomerStocksVM>();
   var stocks = _repositories.GetStocksByClientProfileId(Id);

   var result = from stock in stocks
               select new StocksVM()
               {
                   Code = stock.Code,
                    Name = stock.Name
               };

    model = result.ToList();

    return Json(new
    {
        customerstocks = model
    },JsonRequestBehavior.AllowGet);
}

Javascript:

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {

    $scope.reverse = true;
    $scope.sortBy = function (propertyName) {
        $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
        $scope.propertyName = propertyName;
    };

    $http({
        method: 'POST',
        url: 'GetStocksByCustomer'
    })
    .then(function (response) {
        console.log(response);
        $scope.customerstocks = response.data.customerstocks ;

    }, function (error) {
        console.log(error);
    });
}]);

Answer №1

 $http({
        url: 'specific-url-endpoint',
        method: "POST",
        data: { 'identifier' : uniqueId }
    })
    .then(function(response) {
            // operation successful
    }, 
    function(response) { // can be omitted
            // operation failed
    });

Answer №2

If you're looking to RETRIEVE data from the backend, opt for http.get instead:

javascript:

 function  FetchStocksByUserId(id) {
    return $http.get("FetchStocksByUser", { params: { "id": 
   id} })
   .then(function (response) {
       return response.data
    }) 
    .catch();
}

Place your http requests within an angular service

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

JQuery addClass function not functioning properly when used in conjunction with an AJAX request

I have a website where I've implemented an AJAX pagination system. Additionally, I've included a JQUERY call to add a class to certain list items within my document ready function. $(document).ready(function(){ $(".products ul li:nth-child(3 ...

Vue component fails to register

In my current project, I am incorporating a custom component tag using Vue.JS. Although we have successfully utilized Vue.JS in past projects, the same approach isn't working this time. It seems like I must have overlooked something... After inspect ...

When utilizing fs.writefile with an object, the output will be [object object]

I need assistance with transferring form data to a json file for the first time. After running my code, the json file only shows [object Object] instead of the expected email, username, and password values. Below is my server-side code (expressjs): app.p ...

What is the process for assigning an identification property to a File?

Currently, I have an input field where users can upload files. The uploaded files are displayed as a list showing the file name. However, when I attempt to add an id property to a file, it seems to lose all its properties except for the path property. An ...

Leveraging JavaScript for pricing calculations within asp.net framework

I am currently working with a textbox in a gridview and trying to calculate values using JavaScript. My code seems to be error-free. The goal is to multiply the quantity by the rate to get the total price. function totalise(price, rate, qt) { var qt ...

Vue.js: Utilizing anonymous functions within props object

Looking to enhance the select2 example to make it more practical, I have added multiselect functionality and am now exploring custom select2 configuration options. Check out my progress on jsFiddle Encountering an issue where function properties of props ...

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...

The issue with calling Ajax on button click inside a div container is that the jQuery dialog box is

Here is the code for my custom dialog box: $("#manageGroupShow").dialog({resizable: false, draggable: false, position:['center',150], title: "Manage Group", width:"50%", modal: true, show: { effect:"drop", duration:1000, direction:"up" }, hide: ...

Efficiently load asynchronous content using AngularJS 1.6 in conjunction with the jQuery Steps plugin

Having an issue where, after dynamically loading HTML content asynchronously using the jQuery Steps plugin: <section data-mode="async" data-url="test.html"></section> The AngularJS is failing to detect the content, causing elements with ng-sh ...

How can I use Angular to add ng-class to a parent element when a checkbox is selected?

I am working on a parent list with a dropdown of checkboxes that only shows when you click on the list. Currently, all lists receive the class "active" if any checkbox in any list is checked. However, I want to change this behavior so that only the list co ...

Vue components are unable to access data within methods or computed properties

Within my Vue component, I initially set a boolean constant in the data object with a value of false. Now, I aim to create a method that will change this constant to true and conditionally bind certain elements in the template based on this change. Howev ...

Navigating through various div elements in Javascript and sending parameters to a script

Context In my project, I am using PHP to generate a series of voting sections. Each section follows the same format except for a unique number assigned to it, which increases with each iteration of the PHP loop. To keep track of the unique numbers, I uti ...

Tips for updating an element in an array by using another element from a separate array

What is the objective? We have two arrays: orders and NewOrders We need to check for any orders with the same order_id in both arrays. If there is a match, we then compare the order status. If the order from the NewOrders array has a different status, w ...

Issue: why is EPIPE being written on sendFile()?

Utilizing the html-pdf module for PDF generation, the code snippet below is what I am using: var ejs = require('ejs'); var fs = require('fs'); var pdf = require('html-pdf'); var build = function (template, data) { var ht ...

Navigating point on sphere with celestial coordinates in three js

Currently, I am attempting to animate a point moving randomly across the surface of a sphere. My approach involves generating random spherical coordinates and then converting them into 3D locations using the function .setFromSphericalCoords(). This is the ...

Exploring Angular 4.0: How to Loop through Numerous Input Fields

I am looking to loop through several input fields that are defined in two different ways: <input placeholder="Name" name="name" value="x.y"> <input placeholder="Description" name="description" value"x.z"> <!-- And more fields --> or lik ...

Vue Class Component: The super expression must be null or a function, not undefined

In a peculiar scenario, I have a controls component that contains a menu component which, in turn, includes another controls component without a menu. It may seem strange, but that's just how it's designed. Here's what I'm trying to ac ...

Repeated entry and exit events occurring in text boxes

In my C# Windows form, there are three textboxes: textBuyPrice, textSell, and textMargin. The user can input a Buy Price, and if they enter a Sell Price, the code will automatically calculate the Margin. Similarly, if the user inputs a Margin, the code wil ...

PHP scheduler alternative

I have a PHP script called updater.php that performs a task for 1-2 minutes. It is crucial for the script to complete its job. While I can schedule it with cron, I have come up with an alternative solution. The script should only run at specific times wh ...

Which pattern should be employed to monitor the performance of a model while it is making an ajax request

In my Item model, I have async methods such as delete, rename, etc. Whenever one of these methods is being executed, I display a spinner on the views to indicate loading. Since there are multiple async methods in the Item model, I find myself repetitively ...