我有一个HTML格式,当提交时使用jQuery.ajax()调用服务器;像这样...
$.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.
}
});
它调用的MVC操作接受params并发回一个JSON的负载,它显示在可爱的表格中......一切正常。
我现在需要引入一个按钮,它会以CSV格式发回结果。
所以我使用完全相同的方法......
[1] $('#myForm')。serializeObject()
[2] JSON.stringify [1]
的结果...但是我在[2]的结果上添加了使用$ .param()的步骤....
window.location.replace('/MyArea/MyController/DownloadCSV?' + $.param(JSON.stringify($('#myForm').serializeObject()), true));
除非表格中包含日期,否则一切正常。
看着提琴手我可以看到请求看起来像这样......
/MyArea/MyController/DownloadCSV?referenceNo=102&startDate=01%2F04%2F2011+00%3A00&endDate=31%2F10%2F2011+23%3A59&pageNo=0&pageSize=15&sortBy=&sortDir=true
....我得到500错误....
The parameters dictionary contains a null entry for parameter 'endDate' of non-nullable type 'System.DateTime' for method
如果我删除了对日期的需求,那么一切正常。
任何想法我怎样才能使这个工作?
我正在使用最新的jQuery和MVC3
非常感谢
答案 0 :(得分:1)
在GET请求中,默认模型绑定器期望使用不变文化格式来格式化日期。您的请求应如下所示:
/MyArea/MyController/DownloadCSV?referenceNo=102&startDate=2011-04-01&endDate=2011-10-31&pageNo=0&pageSize=15&sortBy=&sortDir=true
这显然假设您有相应的控制器操作:
public ActionResult DownloadCSV(SomeViewModel model)
{
...
}
SomeViewModel:
public class SomeViewModel
{
public int ReferenceNo { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int PageNo { get; set; }
public int PageSize { get; set; }
public string SortBy { get; set; }
public string SortDir { get; set; }
}
此外,您的AJAX请求似乎有点过于复杂。您无需转换为JSON。以下内容可以正常使用:
var form = $('#myForm');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function (data) {
// Output the results to a table.
}
});