GeorgeD GeorgeD - 2 months ago 8
AngularJS Question

Angular Form to C# MVC Entity Controller null values

TRying to send data from angularjs to C# mvc controller. Although data are collected well(I see them with console.log), they do not receive well in the C# controller and so, null values are stored in the database..
Here is my Angular code:

var formapp = angular.module("formapp", []);
formapp.controller("formctrl", function ($scope, $http) {
$scope.submitFormAngular = function () {
var animal = $scope.animal;
var url = '/Home/AngularData';
$http({
method: 'POST',
url: url,
data: animal,
}).success(function (data) {
console.log($scope.animal);
console.log("worked");
})
.error(function (error) {
console.log("not worked");
});
}
});


here is my C# DTO:

public class Animal
{
[Key]
public int animalID { get; set; }
public string animalName { get; set; }
public string animalHabitat { get; set; }
public string animalClass { get; set; }

}


and finally this is my C# controller:

public JsonResult AngularData(Animal animal)
{
db.Animals.Add(animal);
db.SaveChanges();
return Json(new { foo = "bar", baz = "Blech" });
}


Again: even values are stored in the UI, they do not pass to the C# code.
I a new in Angular etc.
Any help is welcome.

This is my html code for the form:

<div class="form-group">
<label for="name" class="col-md-3 text-align-right"><strong>Name</strong></label>
<input name="name"
id="name"
type="text"
maxlength="80"
ng-model="animal.name"
required
placeholder="write a name" />
<!-- data-ng-change="getFormData(animal)">-->
</div>

<div class="form-group">
<label for="habitat" class="col-md-3 text-align-right"><strong>Habitat</strong></label>
<input name="habitat"
id="habitat"
type="text"
ng-model="animal.habitat"
required
placeholder="write a habitat" />
<!-- data-ng-change="getFormData(animal)">-->
</div>

<div class="form-group">
<label for="class" class="col-md-3 text-align-right"><strong>Class</strong></label>
<input name="class"
id="class"
type="text"
ng-model="animal.class"
required
placeholder="write a class" />
<!-- data-ng-change="getFormData(animal)">-->
</div>

Answer

Worked with GeorgeD and figured out that he had his angular form models defined as

ng-model='animal.name'

instead of

ng-model='animal.animalName'

Changing this fixed it.