I am trying to send data as a model from an html form to a Controller method. I am, however, unsure of how the jQuery ajax post sends such information to the Controller. The actual error I get when I submit the form is:
The resource could not be found… Requested URL: /OnCallSchedule
I know the address is correct, so I suspect that the data being passed does not match the model passed to the controller method:
[HttpPost]
public JsonResult getSchedule(DateModel dateMod)
{
...
return Json(data);
}
The ajax code is:
$(function () {
$('form').submit(function () {
alert('@Url.Action("getSchedule")');
var date = $('form').serialize();
var jqxhr = $.post('@Url.Action("getSchedule")', date, function (data) {
alert("success!");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
jqxhr.complete(function() { alert("second complete"); });
});
});
The first alert statement, listing the path to the method, successfully triggers. After that, the error message pops up, and no other alerts appear.
It should be noted that I have tried this using just about every tactic, so I suspect that I am not sending the data correctly using the serialize() command. What am I doing wrong?
It’s also likely that I am not performing the jqxhr actions correctly. The only place I could find understandable examples are in the jQuery documentation. I was originally using something like:
$.ajax({
url: '/OnCallSchedule/getSchedule',
type: 'POST',
dataType: 'json',
data: $('form').serialize(),
contentType: 'application/json; charset=utf-8',
success: function(data) {
$("#dataTable").html(data);
}
});
I figured out my problem. I am using the MVC style of forms (namely
@Html.BeginForm), which was automatically calling out for a controller action. I was not successfully subverting this functionality, so the ajax code I wrote was pointless. I ended up doing away with the ajax function and@Html.BeginFormaltogether, in favor of@Ajax.BeginForm. Specifically:I learned the hard way that MVC doesn’t always play nice with functionality that its framework doesn’t support.