0

我有一个 ajax 发布请求:

  function downloadElevationMap() {
    var jsonData = ko.toJSON(mod.SelectedItem);
    $.ajax({
        url: '/Home/GetData/',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: jsonData,
        success: function (data) {
            console.log("OK");
        },
    });
}

控制器方法接收数据正确。代码如下:

public FileStreamResult GetData(Mv jsonData)
        {
            var resultAll = jsonData.Data.Select(d => d.y).ToList();
            var str = new StringBuilder();
            _fileName = "ses"+jsonData.Path;
            foreach (var d in resultAll)
            {
                str.Append(d + " ");
            }
            var byteArray = Encoding.ASCII.GetBytes(str.ToString());
            var stream = new MemoryStream(byteArray);
            return File(stream, "text/plain", string.Format("{0}.txt", _fileName));
        }

Mv - 是我的代表数据的类。调试时两者str和流variable都包含正确的数据。

函数downloadElevationMap()被调用onclick="downloadElevationMap()"

我只想在downloadElevationMap()调用GetData控制器时返回一个文件以供下载。但根本什么也没发生。错误在哪里?

4

2 回答 2

2

好吧,你不需要 ajax 来试试这个

window.location="download.action?para1=value1...."

根据您的需要,您可以做这样的事情

window.location="/Home/GetData/?"+$.param(jsonData )
于 2013-10-20T18:02:49.360 回答
1

I'm fairly sure what you are doing is swallowing the data in the success callback in the AJAX call - all your code will do is download the file, call the success callback, and then just print "OK" to the console.

As Anto said, you don't need AJAX (and, indeed, should not be using AJAX) for this. His answer is absolutely correct, provided you can use a GET string. If you need to use a POST request, create a form with hidden inputs and submit that - something like:

HTML

<form action="/Home/GetData" method="POST" id="dataToSubmit">
   <input type="hidden" name="param1" value="value1" />
   <input type="hidden" name="param2" value="value2" />
   <input type="hidden" name="param3.param4" value="value3" />
</form>

JS

function downloadElevationMap() {
  // Write code to map your jsonData to your form elements

  $('#dataToSubmit').submit();
}

You could make the form dynamically if you wish. You might be able to update your page to post directly with a submit button.

One final note, you don't need to submit the data as Json. If you have

{
    "param1": "value1",
    "param2": "value2",
    "param3": {
        "param4": "value3"
    }
}

then if you just use the format in the form above, it will submit fine - this reference explains how to submit to deep models.

于 2013-12-27T10:23:15.567 回答