James Gould
James Gould

Reputation: 4712

Ajax POST to MVC Controller always erroring

I have the following Ajax request:

$.ajax({
    url: '/Projects/Index',
    type: 'POST',
    data: data,
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    error: xhr => { swal('From Error!', 'We\'ve saved your hours, thanks for your input!', 'success'); console.log(xhr) },
    success: result => swal('From Success!', 'We\'ve saved your hours, thanks for your input!', 'success')
});

Which, even when the status code is 200, always errors. My controller receives the data and does stuff with it, and then returns View().

Here's my controller action in full:

[HttpPost, ActionName("Index")]
public ActionResult SetHours(HourPostRequest[] data)
{
    foreach(var item in data)
    {
        var correctModel = item.ToEngineerHours(db);
        db.EngineerHours.Add(correctModel);
        db.SaveChanges();
    }

    var eng = db.Engineers.FirstOrDefault(e => e.DomainUsername == User.Identity.Name).ID;
    var test = db.EngineerHours.Where(e => e.EngineerID == eng).ToList();

    return View(test);
}

The data is always intact, received fine and View always returns. I've added in a random test collection to return which is the model of my View:

@model IList<Timesheet.Models.EngineerHours>

I've gone into the Chrome Dev-Tools Network view and the payload is correct, response is 200 and the controller has received the data and returned View.

This means that my SweetAlert2 alerts are always erroring regardless of the success status.

Can anybody spot why this might be happening?

Upvotes: 0

Views: 73

Answers (1)

Andrei
Andrei

Reputation: 56716

You are returning the View(), which is an HTML string at the end of the day. However in your request you specify:

dataType: 'json'

which tells jQuery to expect response as a json formatted string. jQuery sees HTML and is not able to recognize it as a valid json, hence the error.

Upvotes: 1

Related Questions