2011-10-27 29 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