环境:
win10, .NET 6.0
前端向后台传递string型变量
前端:
function PasteSubmit() {// 获取某个input的值var inName = document.getElementById("xx").value;// 获取某个元素的属性值var inSeq = document.getElementById("xxx").getAttribute("xxx");$.ajax({type: 'POST',url: "/Home/PasteSubmit",data: {inName: inName,inSeq: inSeq,},success: function (resp) {console.log(resp);}});}
后台:(HomeController)
[HttpPost]
public ActionResult PasteSubmit() {// 获取数据string name = Request.Form["inName"]; string seq = Request.Form["inSeq"];System.Diagnostics.Trace.WriteLine(name);System.Diagnostics.Trace.WriteLine(seq);// do something// 返回的内容return Content("test");
}
前台向后台传递多个List
说明:先传递三个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 somethingtxtContent.AppendLine(string.Join(",", cstarts));// 可以打印其他的看看return Content(txtContent.ToString(), "text/plain");
}