I have a form in HTML which when submitted makes a call to the server using jQuery.ajax(); like so…
$.ajax({
url: '/MyArea/MyController/Search',
data: JSON.stringify($('#myForm').serializeObject()),
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
// Output the results to a table.
}
});
The MVC action it calls takes the params and sends back a load of JSON which is displayed in lovely table….it all works just fine.
I now need to introduce a button which will send back the results in a CSV format.
So I’m using the exact same method….
[1] $(‘#myForm’).serializeObject()
[2] JSON.stringify the result of [1]
…but I add the step of using $.param() on the result of [2] like so….
window.location.replace('/MyArea/MyController/DownloadCSV?' + $.param(JSON.stringify($('#myForm').serializeObject()), true));
It all works fine unless dates are included the form.
Looking at fiddler I can see that the request looks like this…
/MyArea/MyController/DownloadCSV?referenceNo=102&startDate=01%2F04%2F2011+00%3A00&endDate=31%2F10%2F2011+23%3A59&pageNo=0&pageSize=15&sortBy=&sortDir=true
….and I’m getting a 500 error….
The parameters dictionary contains a null entry for parameter 'endDate' of non-nullable type 'System.DateTime' for method
If I remove the need for the dates then it all works just fine.
Any ideas how can I get this working?
I’m using latest jQuery with MVC3
Many thanks
In GET requests the default model binder expects dates to be formatted using invariant culture format. Your request should look like this:
This obviously assumes that you have a corresponding controller action:
where SomeViewModel:
Also your AJAX request seems a bit overcomplicated. You don’t need to convert into JSON. The following will work just fine: