zl程序教程

您现在的位置是:首页 >  后端

当前栏目

MVC js动态生成from提交数据然后生成文件下载

JS文件下载数据MVC 生成 动态 from
2023-09-14 09:06:38 时间

前台: 点击触发下面事件

var turnForm = document.createElement("form");
//一定要加入到body中!!
document.body.appendChild(turnForm);
turnForm.method = 'post';
turnForm.action = 'GetCSV';
turnForm.target = '_blank';
//创建隐藏表单
var newElement = document.createElement("input");
newElement.setAttribute("name", "csvFrom");
newElement.setAttribute("type", "hidden");
newElement.setAttribute("value", JSON.stringify(saveSiteArray));
turnForm.appendChild(newElement);

turnForm.submit();

 

后台接收:

public ActionResult GetCSV(FormCollection form)
{
try
{
List<AspSiteList> urlList = JsonToObj(form["csvFrom"], typeof(List<AspSiteList>)) as List<AspSiteList>;
List<string> newUrlList = new List<string>();


foreach (var item in urlList)
{
string newUrl = item.ClientId + " " + item.UneiUserName + " " + item.AsId + " " + item.AsNm + " " + item.Url;
newUrlList.Add(newUrl);
}
string newString = string.Join("\r\n", newUrlList);

 Encoding encoder = Encoding.UTF8;

byte[] bytes = encoder.GetBytes(newString);

Response.Charset = "UTF-8";

Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentType = "application/octet-stream";

Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode("demo.csv"));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
return new EmptyResult();
}
catch (Exception)
{

throw;
}
}