简体   繁体   中英

Pass FormData from Angular to .NET MVC Controller

My View:

<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>

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');
        });
    }
}

So I'm encountering many problems when trying to send data from the frontend with Angular, to the ActionResult in the .Net controller on the backend.

  1. When I use the $http object to send $scope.formData (which is loaded automatically), .Net doesn't recognize the data because it is not formatted as the expected form-data.

  2. When I use the FormData JS object, I get the server error: "Invalid JSON primitive: ------WebKitFormBoundaryzFvk65uKpr0Z7LG1."

  3. If I stringify the FormData object we're back the the first problem.

Many other sources/questions suggest that just passing the FormData object to the ajax request should work -- no information on why the error from 2. is occuring.

Anyone know why this is happpening?

No one came up with a solution to this, but fortunately I did. You need to use the jquery $.ajax method, which accepts optional parameters that Angular's $http doesn't. The final code looks like this:

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');
});

Thanks to this article which helped clear some of this up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM