What is the best way to transfer an object from the view to the controller in AngularJS and ASP.net MVC

How to pass an object with a specific amount of data from the View to the Controller using ASP.net MVC and AngularJS

VIEW

var Person = {};
Person.IdPerson = 69425;
Person.Year = new Date().getFullYear();

$http.post('/API/Update_Person', { params: { Person: Person } }).then(function (response) {

});

CONTROLLER

public JsonResult Update_Person(ModelPerson Person)
{
    var person = (from c in db.Person where c.IdPerson == Person.IdPerson && c.Year == Person.Year select c).FirstOrDefault();

    return new JsonResult { Data = "OK", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Is there a better approach than this?

$http({
    method: "post",
    url: "/API/Person",
    datatype: "json",
    data: JSON.stringify(Person)
}).then(function (response) {

});

Answer №1

Here is a useful tip for sending data to an API controller:

let user = {};
user.userId = 12345;
user.email = 'example@example.com';

$http.post('/API/Send_User_Data', user, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(function (response) {
                    console.log(response);
                }, function(error){
                    console.log(error);
                });

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

Is express.js capable of serving static assets and RESTful APIs at the same time?

Currently, I am using the serve-static package to serve a basic Angular single page application (SPA), but now I need to add functionality to fetch dynamic data from the server. After doing some research, it seems like replacing the "serve-static" module ...

Access a specific JSON value using AngularJS

When using AngularJS to read a specific JSON value, I encountered the following issue: $http({method: 'GET', url: urlVersion}). success(function(data, status, headers, config) { console.log("success data " + status); $scope.ext = data.ve ...

Clicking on the modal button causes the code to run multiple times in JQuery and JavaScript

Hello, I'm experiencing an issue where the code inside a modal is being executed multiple times when the modal button is clicked. For example, if I click the modal button once, the code runs once; if I click it twice, the code runs twice, and so on. ...

Receiving a conduit from the fuel supplier with only limited information on hand

I am designing a service that will utilize pipes as templates. In order to accomplish this, I require access to the registered pipes. The final code structure should resemble the following: @Injectable() class MyService { constructor(private injector ...

Pressing a shortcut key will direct the focus to the select tag with the help of Angular

I was trying to set up a key shortcut (shift + c) that would focus on the select tag in my form when pressed, similar to how tab works. Here is the HTML code for my form's select tag: <select id="myOptions"> <option selected> Opti ...

Guide to making an interactive graph in MVC4

I am working on an asp.net mvc4 application and trying to add a chart to display data. However, when I try to view it in the browser, nothing appears. Below is the code snippet from the controller that is functioning correctly: DAL dal = new ...

Package.json file is not included in Typescript

Each time I execute tsc, it converts the files to JS format successfully, except for package.json. I want this file included in my output directory. Currently, my tsconfig.json looks like this: { "exclude": ["node_modules"], "compilerOptions": { " ...

Utilizing React Typescript to Efficiently Manage Multiple Checkboxes within a List

I'm working on a scenario where I have to manage multiple checkboxes in a list Only one checkbox can be selected at a time For example, if I toggle on Checkbox 1 and then click on Checkbox 2 - I want to automatically toggle off Checkbox 1 as I toggl ...

The issue of file uploading not functioning properly with AngularJS on a lighttpd server is causing frustration

Currently in my project, we are utilizing the lighttpd server. I am attempting to upload a file and encountering two Response Headers. The first has a 301 status code (Moved Permanently) and the second has a 200 status code (OK). However, upon checking th ...

How can I pass additional props that are not specified in the interface while working with a React TS component?

I am working with a TS React component called MyButton.tsx: import React from 'react' interface MyButtonProps { children: JSX.Element | JSX.Element[], className?: string, variant?: 'big-button' | 'medium-button' | &apos ...

Strange behavior observed when transclusion is used without cloning

During my experimentation with transclusion, I wanted to test whether the transcluded directive could successfully locate its required parent directive controller after being transcluded under it. The directives used in this experiment are as follows: - Th ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

The function $http.get in AngularJS is providing an undefined response

In the process of developing a small Angular application, I started with this seed project: https://github.com/angular/angular-seed. The only modifications I made were to the following files: /app/view1/view1.js 'use strict'; angular.mod ...

Guide on how to designate an initial page in an Ionic project

I apologize if this question seems basic, as I am still relatively new to this. While I have a fundamental grasp of how navigation works with angular js, I am struggling to set a starting page. My goal is to make the login page the initial landing page, an ...

Avoiding duplication when using LoopbackJS and the AngularJS SDK to save models is important

I am working with LoopBackJS AngularJS SDK and have a model for sites (id(pk) integer, name varchar(50), url varchar(100)). However, when I attempt to update the name field and call site.save(), the record ends up being duplicated. If I try to update any ...

Switching from dark mode to light mode when reloading or navigating to a new page

Hello everyone. I've successfully implemented a dark mode toggle on my website, but I'm facing an issue where the mode resets whenever I navigate to a new page or refresh the current page. Can anyone help me figure out how to prevent this from ...

Error message: The database query function is encountering an issue where the property 'relation.referencedTable' is undefined and cannot be accessed

Currently, I am working with two schemas named products.ts and category.ts. The relationship between these files is defined as one-to-many. In the products.ts file: import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core"; import ...

Enhancing Security and Privacy of User Information with JWT Tokens and NgRx Integration in Angular Application

I'm facing a security concern with my Angular application. Currently, I store user details like isAdmin, isLoggedIn, email, and more in local storage. However, I'm worried about the risks of unauthorized updates to this data, especially since my ...

Using custom class instances or objects within Angular controllers is a simple process

Using three.js, I have created a class called threeDimView that houses my scene, camera, and other elements. In my JavaScript code, I instantiate a global object of this class named threeDimView_. threeDimView_ = new threeDimView(); Now, I wish to displa ...

Leveraging AnimatePresence from the Framer Motion library to design an exit animation for a motion.div

My goal is to implement a side menu that smoothly slides in and out when the menu/close button is clicked using framer motion. Initially, clicking on the menu button will cause the menu to slide out from the left side of the screen while changing the butto ...