I have set up an API controller to manage an ajax request. Each time the Ajax request is sent from the script below, I encounter a 500 error:
POST http://localhost:58463/api/Reservations 500 (Internal Server Error) jquery-2.1.0.min.js:4
l.cors.a.crossDomain.send jquery-2.1.0.min.js:4
o.extend.ajax jquery-2.1.0.min.js:4
(anonymous function) Confirm?spaceNumber=5:129
o.event.dispatch jquery-2.1.0.min.js:3
r.handle
The strange thing is that - despite the error message - the request actually goes through and creates a reservation. How is this possible, and how can I fix the error?
View:
@model *********.Models.Reservation
@section Scripts {
$(document).ready(function () {
console.log('ready');
$('#confirmationForm').submit(function (event) {
event.preventDefault();
var $form = $(this);
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize(),
dataType: "json",
traditional: true,
success: function (response) {
console.log('yes!');
},
error: function(response) {
console.log('no');
}
});
});
});
}
<div class="section about" style="height: 100%;">
<div id="main-content" class="main-content">
<div class="container">
<div class="section-heading">
<h2 class="red">Confirm Your Reservation</h2><br />
</div>
<div class="section-content">
<div class="row">
<div class="hero-buttons text-center">
<a href="#" class="btn btn-gray btn-lg white">No</a>
<form action="/api/Reservations" method="post" id="confirmationForm">
@Html.Hidden("UserName", @Model.UserName)
@Html.Hidden("SpaceNumber", @Model.SpaceNumber)
<input type="submit" value="Yes" class="btn btn-red btn-lg white">
</form>
</div>
</div>
</div>
</div>
</div>
</div>
APIController:
public class ReservationsController : ApiController
{
private MyContext db = new MyContext();
// POST api/Reservations
public HttpResponseMessage PostReservation(Reservation reservation)
{
if (ModelState.IsValid)
{
reservation.Game = db.Games.FirstOrDefault(g => g.ID == AppSettings.CurrentGameID);
db.Reservations.Add(reservation);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, reservation);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = reservation.ID }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
}
Solution
heymega guided me in investigating further into the 500 error I was encountering. With the help of FireBug, I discovered this information in the exception message:
"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."
To resolve this issue, I added these lines to my WebApiConfig.cs file:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);