I have an ajax POST request that is supposed to be submitting data to an ASP.NET MVC action. This works fine 95% of the time but every so often, for whatever reason, my FormCollection is empty and the application errors out as a result.
I would have included the raw request values however I haven’t been able to reproduce this myself.
My ajax call looks like this:
var data = {};
data.Property = 123; // etc
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
success: function(viewModel) {
// do stuff
}
});
What would cause the FormCollection to intermittently be empty on the ajax POST?
I have suspected things like session timeouts and the like but I would expect that to error out before I get in to the action.
First of all you seem to be sending a JSON request (
JSON.stringify(data)). This is not supported out of the box in ASP.NET MVC 2. It is in ASP.NET MVC 3 that aJsonValueProviderFactorywas introduced. You may take a look at the following article which explains in more details JSON requests in ASP.NET MVC.Also everytime you want to send a JSON request you should set the proper content type using the
contentTypeparameter:and last but not least I would recommend you to use view models instead of relying on some weakly typed structures such as FormCollection in your controller actions and having to write plumbing code.
UPDATE:
FormCollectionis a key/value pair collection. So if you want to use it (despite my recommendation against it) you should not use a JSON request. You should use a normal key value request. So remove the JSON.stringify from your AJAX request and remove the contentType: ‘application/json’ parameter as well. There’s really no point in using weakly typed key/value pair collection with JSON objects.