I am attempting to use AngularJS to update some data using the $http.put method. However, I have tried several variations on calling this method and it has repeatedly failed to call the put method in my controller - or, if it does, it creates a new entity rather than updating the old data. Here is my code:
(I know the rest of my api works as post and get work fine for cars)
CarController.cs
public void Put(int CarId, [FromBody] Car c)
{
System.Diagnostics.Debug.WriteLine("CarController.Put() Called");
c.CarId = CarId;
if (!_repo.UpdateCar(c) || !_repo.Save())
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
Repository ("_repo"):
public bool UpdateCar(Car car)
{
if (car == null)
{
throw new ArgumentNullException("car");
}
int index = _ctx.Cars.ToList().FindIndex(c => c.CarId == car.CarId);
if (index == -1)
{
return false;
}
_ctx.Cars.ToList().RemoveAt(index);
_ctx.Cars.Add(car);
return true;
}
AngularJS script:
var _linkPersonAndCar = function(person, car) {
var deferred = $q.defer();
alert("_linkPersonAndCar()\nPerson = " + JSON.stringify(person) + "\nCar = " + JSON.stringify(car));
//Update car
car.persons.splice(0, 0, person);
alert("_linkPersonAndCar() attempting put");
$http.put("/api/cars/"+car.carId, car)
.then(function ()
{
alert("_linkPersonAndCar() - Success!");
deferred.resolve();
},
function ()
{
alert("_linkPersonAndCar() - Failure updating car");
deferred.reject();
});
alert("_linkPersonAndCar() - Complete");
return deferred.promise;
};