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.
Using the $http object to send $scope.formData results in .Net not recognizing the data because it is not formatted as expected form-data.
When utilizing the FormData JS object, I encounter a server error: "Invalid JSON primitive: ------WebKitFormBoundaryzFvk65uKpr0Z7LG1."
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?