Jquery.ajax not positioning data correctly in asp.net mvc site - formcollection empty
I am using jquery to submit my form (here the id is #myForm) like this:
$(document).ready(function() {
$("#my_form").submit(function(event) {
$.ajax(
{
type: "POST",
url: $("#my_form").attr("action"),
contentType: "application/json; charset=utf-8",
data: ("#my_form").serialize(),
success: function(result) {
alert('hi');
},
error: function(req, status, error) {
alert("Sorry! We could not process the form at this time.");
}
}
);
event.preventDefault();
});//end submit for my_form
});//end document ready
If I go through the posted data I see the following
POST / PageContents / Edit HTTP / 1.1
x-request-with: XMLHttpRequest
Accept language: ru-us
Referer: [CHANGE ME]
Accept: /
Content-Type: application / json; encoding = UTF-8
Accept-Encoding: gzip, deflate
User-Agent: Mozilla / 4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident / 4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Host: www.somesite.com:3852
Content-length: 142
Connection: Keep-Alive
Pragma: no-cache
ID = 1 & small_title = Welcome + for !!! & big_title = Chicago !!! & body = here + will be + some + things + for + in + body !!! &. Subtitle = + space + for + pizza !!
But this fails for the correct action because the Request.Forms collection is empty.
If I submit this form without javascript and just use normal HTML, the posted data looks like this:
POST / PageContents / Edit HTTP / 1.1
Accept: image / gif, image / jpeg, image / pjpeg, image / pjpeg, application / x-shockwave-flash, application / x-ms-application, application / x-ms-xbap, application / vnd.ms-xpsdocument, application / xaml + xml, /
Referer: [CHANGE ME]
Accept language: ru-us
User-Agent: Mozilla / 4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident / 4.0 ;. NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Content-Type: application / x-www-form-urlencoded
Accept-Encoding : gzip, deflate
Host: www.somesite.com:3852
Content-Length: 164
Connection: Keep-Alive
Pragma: no-cache
small_title = Welcome + up to% 21% 21% 21 & big_title = Chicago% 21% 21% 21 & subtitle = + space + for + pizza% 21% 21 & body = here + going + some + things + for + body +% 21% 21% 21 & id = 1
You can see that the data is being laid out correctly so that my routing works and the correct action is called.
All fields in my form do have a name attribute.
Thanks and sorry for the long post.
source to share