2011-10-27 45 views
0

我有一个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结果]

...但我加上的结果,使用$ .PARAM()的步骤[2]像这样....

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

非常感谢

回答

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. 
    } 
}); 
+0

感谢您的建议达林。我已经重新调整了一些东西,现在正在努力工作。 – ETFairfax