eddie_cat eddie_cat - 28 days ago 8
jQuery Question

Why isn't my post method hitting the controller?

I am just trying to send a simple model back to my controller to update an object. For some reason this is evading me.

Controller method:

[Authorize(Roles = Enums.Roles.SiteAdmin)]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "BuildingId,Name")] Building building)
{
if (ModelState.IsValid)
{
service.Update(building);
return Json(new { Status = "Success!" });
}

return Json(new { Status = "error." });
}


EF model:

public class Building
{
[Key()]
public int BuildingId { get; set; }

[Required()]
[MaxLength(200)]
public string Name { get; set; }

public virtual ICollection<Room> Rooms { get; set; }
}


Javascript post method:

$('.saveOnBlur').on('blur', function (e) {
var newBuildingName = $(this).prop("innerText");
var editBuildingId = $(this).siblings('.hiddenId').children().first().val();

var modifiedBuilding = { BuildingId: Number(editBuildingId), Name: newBuildingName };

$.ajax({
url: "/Equipment/Buildings/Edit",
type: 'POST',
contentType: 'application/json',
data: { building: JSON.stringify(modifiedBuilding) }
});
})


I don't know what I'm doing wrong. I am able to create objects using a very similar approach, but this code doesn't even hit the controller method, I just immediately get an internal error 500 (not 404). Any ideas?

Answer

You will have to debug. It could be ValidateAntiForgeryToken, if you do not provide a valid value it will stop before it even reaches your code. I do not see any javascript code that includes a value in the http header.

To trouble-shoot comment it out and see if it hits the method. If not try the next filter which is your authorization filter and see if that is causing your code not to be executed.

If you already have code to handle tokens sent over ajax great, if not there are a lot of previous questions with good answers on SO which describe how you can do it like by creating a modified ValidateAntiForgeryTokenAttribute that reads it from the http header.


Additional things to check.

  1. change the data payload to data: JSON.stringify(modifiedBuilding)
  2. check your route as well /Equipment/Buildings/Edit. You can provide the routing configuration in your question to make it easier.