eddie_cat eddie_cat - 2 months ago 10
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)]
public ActionResult Edit([Bind(Include = "BuildingId,Name")] Building building)
if (ModelState.IsValid)
return Json(new { Status = "Success!" });

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

EF model:

public class Building
public int BuildingId { get; set; }

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 };

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?


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.