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

前台: 点击触发下面事件

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;
}
}

posted @ 2017-06-15 15:01  公众号python学习开发  阅读(178)  评论(0编辑  收藏  举报