Transmitting FormData from Angular to a .NET MVC Controller

Here's my perspective:

<form ng-submit="onFormSubmit()">
    <div class="form-group">
        <label for="Movie_Genre">Genre</label>
        @Html.DropDownListFor(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Name"), "Select Genre", new { @class = "form-control", ng_model = "formData.Movie.GenreId" })
        @Html.ValidationMessageFor(m => m.Movie.GenreId, "The Genre field is required.")
    </div>
    <div class="form-group">
        <label for="Movie_Stock">Number in Stock</label>
        @Html.TextBoxFor(m => m.Movie.Stock, new { @class = "form-control", ng_model = "formData.Movie.Stock" })
        @Html.ValidationMessageFor(m => m.Movie.Stock)
    </div>

    @Html.HiddenFor(m => m.Movie.Id, new { ng_model = "formData.Movie.Id" })
    @Html.AntiForgeryToken()
    <button type="submit" class="btn btn-primary">Save</button>
</form>

This is how I handle it in my Angular Controller:

var MoviesAdminEditController = function ($scope, $state, $http) {
    $scope.formData = {};

    $scope.onFormSubmit = function () {
        // $scope.formData.__RequestVerificationToken = angular.element('input[name="__RequestVerificationToken"]').attr('value');

        var formData = new FormData(angular.element('form'));
        formData.append('__RequestVerificationToken', angular.element('input[name="__RequestVerificationToken"]').attr('value'));

        $http({
            method: 'POST',
            url: '../../Movies/Save',
            data: formData,
            headers: {
                'enctype': 'multipart/form-data'
            }
        }).then(function successCallback(response) {
            alert('worked');
            $state.go('moviesAdmin');
        }, function errorCallback(response) {
            alert('failed');
            $state.go('moviesAdmin');
        });
    }
}

I'm facing a few challenges when trying to transmit data from the frontend using Angular to the ActionResult in the .Net controller on the backend.

  1. Using the $http object to send $scope.formData results in .Net not recognizing the data because it is not formatted as expected form-data.

  2. When utilizing the FormData JS object, I encounter a server error: "Invalid JSON primitive: ------WebKitFormBoundaryzFvk65uKpr0Z7LG1."

  3. If I stringify the FormData object, we're back to the initial problem.

Although other sources and questions propose that simply passing the FormData object to the ajax request should work, there is no clarification on why the error mentioned in point 2 occurs.

Does anyone have insights into why this issue is happening?

Answer №1

Despite no one providing a solution to this problem, I was able to figure it out. The key is using the jquery $.ajax method instead of Angular's $http since it allows for additional parameters that are necessary in this case. Here is the final code snippet:

var formData = new FormData(angular.element('#new-movie-form')[0]);

$.ajax({
    type: 'POST',
    data: formData,
    url: '../../Movies/Save',
    processData: false,
    contentType: false,
    cache: false,
    dataType: 'json'
})
.done(function () {
    alert('success');
    $state.go('moviesAdmin');
})
.fail(function () {
    alert('failed');
    $state.go('moviesAdmin');
});

I want to give credit to this helpful article that guided me through resolving this issue.

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

Encountered an ERESOLVE error when attempting to install a package, unable to resolve the dependency tree

After attempting to install the necessary dependencies for my project with npm install, an error message came up that I am unable to decipher: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: &l ...

Exploring the Angular approach to accessing the ng-repeat value from within a directive

I am looking to create a list generated by ng-repeat. Each item in the list will have a name and an input field for a number. My goal is to be able to update this number using a directive, but I'm unsure of how to access this value from within the di ...

jQuery click event not working post Ajax request returned a 403 error

I am facing an issue with my ajax request where I receive a 403 error message. Strangely, when this error occurs, the click() function associated with the ajax call stops working. There is no manipulation of HTML elements before or after the ajax call, and ...

I am encountering an issue with the functionality of my button display and hide feature in my code

I have a button that toggles between my favorite items and I want it to change its appearance when clicked. The button should be updated after a successful ajax call. However, the issue I am facing is that when I click on the hide button, the show button ...

Manipulating Strings in JavaScript

Hi there, I'm a beginner in JavaScript and I could really use some help with the following question. So, let's say I have this string: "AB_CD.1.23.3-609.7.8.EF_HI.XBXB" The numbers 1.23.3 and 609.7.8 are completely random with two dots separat ...

The resizing of the window does not trigger any changes in the jQuery functions

Here is a snippet of jQuery code that executes one function when the window size is large (>=1024) and another when it is resized to be small. Although the console.logs behave as expected on resize, the functions themselves do not change. This means th ...

Conflict between iOS 7+ swipe back gesture and stateChange animations

When transitioning between states in an AngularJS application, I utilize CSS animations to add visual appeal to the view change. This may involve applying fades or transforms using classes like .ng-enter and .ng-leave. In iOS 7+, users can swipe their fin ...

Subject: Exploring the possibilities of Joomla with PHP, Java, and AJAX

I'm primarily a DBA, not really a web developer. However, I am currently attempting to create a intricate website using Joomla. Specifically, I need the user page to be interactive without needing to refresh. Let me try my best to explain. Imagine th ...

Exploring Nextjs with server-side rendering and fetching data from

When utilizing the getServerSideProps function in Next.js to make a fetch request to my API, I encountered an issue where the origin header was coming back as undefined. This seems to be specific to requests made from the server in Next.js, as I am able ...

What is the best way to display a welcoming message only once upon visiting the home page?

After gaining experience working with rails applications for a few months, I have been tasked with adding a feature that displays a welcome message to users visiting the site home page for the first time, but not on subsequent visits or page reloads. What ...

The functionality of Angularjs ui-modal is being affected by issues related to the $http request

Currently, I am incorporating Angularjs 1.5.x along with AngularUI Bootstrap. My goal is to initiate a bootstrap modal and populate it with remote data by making use of $http request. To achieve this, I am utilizing the resolve method within the modal&ap ...

What is the reason for placing a ReactJS component, defined as a function, within tags when using the ReactDom.render() method?

As someone who is brand new to ReactJS and JavaScript, I am struggling to grasp the syntax. The component I have created is very basic: import React from 'react' import ReactDom from 'react-dom' function Greetings() { return <h1&g ...

Retrieving POST data from requests in Node.js

My goal is to extract parameters from a POST request and store them in the variable postData using the request module. I found helpful information on handling post requests with Express.js here. Additionally, I came across this useful thread on how to retr ...

How to send a JSON Object and a CSV file using FormData

I need to send a JSON Object and a CSV file in a fetch request from my frontend to my backend. The JSON object is stored in the headerIngestion variable, while the CSV file is saved in the csv state. let formData = new FormData(); formData.append('h ...

What is causing this get method to return such a message?

One of my functions tabulates user-specific data using a GET method that sends a query parameter userId: <script> let thisArray = [] let = userId = $('#userId').val(); $.ajax({ method:&ap ...

Enhance Material UI with custom properties

Is it possible to add custom props to a Material UI component? I am looking to include additional props beyond what is provided by the API for a specific component. For example, when using Link: https://material-ui.com/api/link/ According to the document ...

Tips for retrieving the most recent UI updates after the container has been modified without the need to refresh the browser

Currently, I have developed a micro frontend application in Angular using module federation. This application is hosted in production with Docker containers. My main concern revolves around how to update the UI changes for the user without them needing to ...

Error: 'require is not defined' pops up while trying to import into App.js for a React App built with CDN links

My latest project involves a React App that showcases an h1 tag saying "Hello World" on the browser. Rather than utilizing npm, I have opted for CDN links to set up the application. The structure of the App consists of three key files: An index.html file ...

Synchronization Issue between Ionic Popover templateURL and Angular ng-model

In my project utilizing the Ionic framework, I encountered an issue with the code snippet below: $scope.loginCountryCode; $scope.loginPhone; // Code continues... <div class="container"> <label class="item item-input&quo ...

Submitting a File Using AngularJS and PHP

Attempting to upload a file utilizing Angular JS and PHP through a formdata object. Wanting to utilize key1 (data) value as JSON to transmit filename and user info to the php script Opting for key2 (uploadFile), value being the file currently being uploa ...