Using ASP.NET MVC 6 Web API along with Angular, a resource can be posted as an object property in the

I am facing a challenge in sending a complex object from Angular to my web API. Here is how the object looks:

{
    Name: "test",
    Tax: 23,
    Addresses: [ {
        country: "ro",
        city: "bucharest"
    },
    {
        country: "fr",
        city "paris"
    }]}

On the server side, I have a model that looks like this:

public class Model {
    public Model (){
        Addresses = new List<Address>();
    }

    public string Name {get; set;}
    public int Tax {get; set;}
    public List<Address> Addresses {get; set;}
}

The Address class has 2 string properties.

In my previous application using MVC5 and AngularJS $http service, the object mapping worked perfectly. However, after transitioning to MVC6 (ASP.NET 5), I am facing an issue where the object on the server side is NULL when I include the array in my JavaScript object. If I remove the array, it works fine. How can I send an array as an object property from AngularJS using $resource service to an MVC6 controller?

Answer №1

Success! After some trial and error, I finally got my code to work. Here's an example of what I did:

test1.html

<!DOCTYPE html>

<html ng-app="myApp">
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
    <script type="text/javascript" src="test1.js"></script>
    <div ng-controller="TestController">
        <div>Test</div>
    </div>
</body>
</html>

test1.js

var myApp = angular.module('myApp', []);

myApp.controller('TestController', ['$scope', '$http', function ($scope, $http) {
    var dataObj = {
        Name: "test",
        Tax: 23,
        Addresses: [{
            country: "ro",
            city: "bucharest"
        },
        {
            country: "fr",
            city: "paris"
        }]
    }
    $http({
        url: 'http://localhost:1522/api/values',
        method: 'POST',
        data: JSON.stringify(dataObj),
        dataType: 'json'
    }).success(function (data) {
        debugger;
        alert("OK");
        //TODO.....
    }).error(function (data) {
        //TODO....
    });
}]);

Check out the screenshot below to see my folder structure and a breakpoint after the POST request:

https://i.sstatic.net/cb93q.png

Don't forget to replace the URLs with your domain and navigate to in your browser to run your Angular app.

P.S.: This example only works when your Angular app and web API are on the same domain. If you need to separate them (e.g., move the Angular app to a different domain or project), you'll need to configure CORS - check out this helpful guide on enabling cross-origin requests (CORS) in ASP.NET 5 & MVC 6.

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

Troubleshooting a problem with a personalized webkit scrollbar in Chrome

Using the CSS property scroll-snap-type: y mandatory; to customize my scrollbar with the following styles: ::-webkit-scrollbar { width: 12px; background: transparent; } ::-webkit-scrollbar-track { background-color: rgba(0, 0, 0, 0.5); -webkit-box-s ...

Having issues installing Parcel through npm - Encountered an error while parsing package.json information

After creating a package.json file using the command npm init in my project folder, I proceeded to run npm i parcel --save-dev which resulted in an error message: C:\Users\XPRESS\Desktop\starter>npm i parcel --save-dev npm ERR! code ...

The function GetURLParameter(sParam) is displaying %20 as blank space in the webpage

I am facing an issue with a code that pulls URL parameters into the landing page. The problem is that it is including white spaces as %20. For example, if my URL parameter is: example.com/?title=my website, it would display my%20website on the page inste ...

Alternatives to AMP in AngularJS

My current project is based on Angular 1.x and I recently received advice from an SEO specialist to enhance the initial mobile load speed of my website. One suggestion was to implement AMP, but after some research, it appears that integrating AMP with Angu ...

Steps for displaying a loading image during the rendering of a drop-down list (but not during data loading):

Using jQuery's autocomplete combobox with a large dataset of around 1,000 items. The data loads smoothly from the server, but there is a delay when expanding the drop-down list to render on screen. Is there a way to capture the initial click event on ...

Flask causing AJAX Request to encounter a CORS Policy issue

Currently, I am utilizing Flask to construct a basic backoffice system. In an attempt to execute some requests on the client-side using AJAX, I keep encountering a persistent error: Access to XMLHttpRequest at '...' from origin 'http://lo ...

Add characters to div using JavaScript

I am curious about which framework, if any, would be most effective for capturing keystrokes and adding them to an HTML element such as a "p" element. My goal is to allow the client to type something on the keyboard and have it immediately displayed in the ...

Is there a way to prevent a user who is already logged in from accessing their account on a different browser or tab

My current stack consists of reactjs, nodejs, and redux for user authentication. I am utilizing aws cognito to handle the user authentication process. The main functionality of my app is uploading files from users to an s3 bucket. One of my goals is to p ...

Using VueJs to invoke a plugin from a .js file

I'm seeking a deeper understanding of working with vueJS. My current setup In my Login.vue component, there is a function logUser() from UserActions.js which in turn calls the postRequest() function from AxiosFacade.js Additionally, I use a plugin ...

Recoil: Executing a function when an atom is modified

My goal is to store a user object in an atom and cache it in localStorage every time it changes to avoid having the user sign in repeatedly if the app crashes: localStorage.setItem('user', JSON.stringify(user)) Previously, with useContext, I ach ...

Ways to update on the status of uploading a video on YouTube

I am currently developing an ASP.NET Web API integrated with Angularjs for client-side programming. The main feature of my application is the ability for users to upload and watch videos. In order to achieve this, I am planning to utilize the YouTube API f ...

Challenge with URL routing in ASP.NET MVC and Angular template design

I have a question regarding the setup of the default login URL in the ASP.net MVC Angular template. The web API URL for login is "Account/Login". I have included an href tag in the layout.cshtml file as shown below: <data-ng-class="{active : activeVi ...

Encountering an ASP.NET Boilerplate Angular Project Issue during npm start

I am utilizing the ASP.NET Boilerplate Framework which is built on .Net Core and Angular. I closely followed the guidelines outlined in this page for the startup template with Angular, but upon running npm start, I encountered the following error message: ...

Is User.Identity.Name an anonymous user with Windows authentication enabled?

I have developed an ASP.NET MVC application that includes a custom AuthorizeAttribute implementation with the following override: protected override bool AuthorizeCore(HttpContextBase httpContext) { return base.AuthorizeCore(httpContext); } However, ...

SmartCollection in Meteor generating unpredictable outcomes

When executing News.insert({name: 'Test'}) in the browser JS console, it caused {{count}} to increase from 0 to 1. Checking in mongo console using mrt mongo, db.news.find().count() also returns 1. However, after adding a record through the mongo ...

The code stored in Github differs from the code deployed on the production server

I recently took over a project that had been outsourced to a web development company in the past, and it's built on the MEAN stack. After struggling to get the code from the Github repository to work properly, I decided to download the code directly ...

Managing various swipe interactions using HTML and JavaScript/jQuery

I'm in the process of creating a mobile multiplayer game using HTML5 and Javascript. The jQuery Plugin "touchwipe" is utilized to manage swipe events in various divs like this: $('#play1').touchwipe({ wipeLeft: function(){ if ...

What is the best way to create a nullable object field in typescript?

Below is a function that is currently working fine: export const optionsFunc: Function = (token: string) => { const options = { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, } ...

Vue 3 - Compelled to utilize any data type with computedRef

Recently, I've been diving into Vue/Typescript and encountered a puzzling error. The issue revolves around a class named UploadableFile: export class UploadableFile { file: File; dimensions: Ref; price: ComputedRef<number>; ... constr ...

Learn the steps for inserting or updating data in a local JSON file solely through JavaScript

Currently, I am in the process of reading a JSON file and removing an element once it finds an exact match. My goal is to then push the remaining data back into the JSON file after deletion. readJsonFile("./objects.json", function(jsonData){ let parsedD ...