说明:先传递三个List,后台接收后做一些处理,然后回传字符串,将字符串写入文件,生成下载文件,自动下载。
前端:
@{
// 定义
List<int> cstarts = new List<int>() { 1, 2, 3};
List<int> cends = new List<int>() { 4, 5, 6 };
List<string> cstrs = new List<string>() { "", "sss", "x"};
}
<!-- html内容略 -->
<button id="exportSeqBtn" onclick="exportSeq()" type="button">
导出序列
</button>
<!-- js -->
<script>
// 导出序列
function exportSeq() {
var starts = @Html.Raw(Json.Encode(cstarts));
var ends = @Html.Raw(Json.Encode(cends));
var strs = @Html.Raw(Json.Encode(cstrs));
$.ajax({
url: "/Home/ExportSeq",
method: 'POST',
data: JSON.stringify({
vid: @Model.Id,
cstarts: starts,
cends: ends,
cstrs: strs,
}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
var blob = new Blob([data], { type: 'text/plain' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'sequence.fa'; // 下载文件的文件名
link.click();
},
error: function (xhr, status, error) {
alert('An error occurred while generating the file: ' + error);
}
});
}
</script>
后端:
[HttpPost]
public ActionResult ExportSeq(string vid, List<int> cstarts, List<int> cends, List<string> cstrs) {
var txtContent = new StringBuilder();
// do something
txtContent.AppendLine(string.Join(",", cstarts));
// 可以打印其他的看看
return Content(txtContent.ToString(), "text/plain");
}