Whenever I use toastr for form notifications, I always seem to receive an error message even though the data is successfully saved in the database. I suspect that the error may be stemming from the controller because I am not sending back in JSON format. Any help would be greatly appreciated.
-----Controller : ---------------
public ActionResult CreateNewRentals(NewRentalDto newRental)
{
var hour = DateTime.Now;
var customer = _context.Customers.Single(
c => c.Id == newRental.CustomerId);
var movies = _context.Movie.Where(
c => newRental.MovieId.Contains(c.Id)).ToList();
foreach (var movie in movies)
{
if (movie.NumberAvailable == 0)
return BadRequest("le film est introuvable");
movie.NumberAvailable--;
var rental = new Rental
{
Customer = customer,
Movie = movie,
DateRented = DateTime.Now
};
_context.Rentals.Add(rental);
}
_context.SaveChanges();
return Ok();
}
----------------La view --------------------
<script type="text/javascript">
$(document).ready(function () {
var vm = {
movieId: []
};
var customers = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: customers,
remote: {
url: '/api/customers?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#customer').typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
name: 'customers',
display: 'name',
source: customers
}).on("typeahead:select", function (e, customer) {
vm.customerId = customer.id;
});
/* MOVIES */
var movies = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/movies?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#movie').typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
name: 'movies',
display: 'name',
source: movies
}).on("typeahead:select", function (e, movie) {
$("#movies").append("<li class='list-group-item'>" + movie.name + "</li>");
$("#movie").typeahead("val", "");
vm.movieId.push(movie.id);
});
$("#newRental").submit(function (e) {
e.preventDefault();
$.ajax({
url: "/api/newRentals",
method: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(vm),
success: function (data) {
toastr.success(' successfully!');
},
error: function () {
toastr.error( 'error!');
}
});
});
});
</script>