1

我正在使用带有 Web API 的 ASP.NET MVC 4。

我希望能够通过单击按钮下载 csv 文件。

下面是我对 api 'exportfruit' 的 jquery 调用

function downloadFile(){
var data = {
    StartDate: this.model.get('StartDate'),
    Name: this.model.get('Name')
};

var form = document.createElement('form');
form.action = 'api/fruitapi/exportFruit';
form.method = 'POST';
form.style.display = 'none';
for (i in data) {
    if (data[i] != "") {
        var inputElement = document.createElement('textarea');
        inputElement.name = i;
        inputElement.value = data[i];
        form.appendChild(inputElement);
    }
}
document.body.appendChild(form);
form.submit();
}

我的 web api 操作如下

[ActionName("ExportFruit")]
public HttpResponseMessage PostExportFruit(SomeModel model)
{
    // for now i am just testing the value returned from model.
    string csv = "some data from db";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StringContent(csv);
    //a text file is actually an octet-stream (pdf, etc)
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    //we used attachment to force download
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = "testfile.csv";
    return result;    
}

现在我面临的问题是我将日期传递为 'dd/mm/yyyy' 但在 web api 操作中它将日期转换为 'mm/dd/yyyy'

例如,

如果我有一个像这样的约会

  • 2012 年 1 月 2 日,这将转换为 2012 年 2 月 1 日
  • 如果 22/10/2012(今天的日期)转换为 01/01/0001

我该如何解决 ?

我在传递我使用这个修复的json数据时遇到了类似的问题,但我不知道如何处理这个问题。

请帮助我,因为互联网上几乎没有任何可用的内容。

4

1 回答 1

1

您可以将 StartDate 的类型 Datetime 更改为 String。

然后,发布到操作,ParseExact 字符串到日期时间

DateTime startDate = DateTime.ParseExact(model.StartDate, "dd/MM/yyyy", null);
DateTime endDate = DateTime.ParseExact(model.EndDate, "dd/MM/yyyy", null);
于 2012-10-22T09:38:10.013 回答