標籤:des style blog http io color ar os sp
在MVC項目中,通常下載的檔案的簡單方式是直接採用 location.href+查詢參數方式。
1 var searchParams = {2 studentName: $("#StudentName").val(),3 birthDate: $("#BirthDate").val()4 };5 var baseurl = "@Url.Action("ExportData", "Student")";6 location.href = baseurl + "?" + $.param(searchParams);View Code
但是對於查詢參數過長時url就會出錯,因為IE瀏覽器對URL的最大限制為2083個字元,如果超過這個數字,提交按鈕沒有任何反應。對於Firefox瀏覽器URL的長度限制為65,536個字元,但當我測試時,最大隻能處理8182個字元,這是因為url的長度除了瀏覽器限制外,還會受Web伺服器的限制。註:可能有些朋友會想當然的認為,如果最大長度限制為2038字元,是不是參數差不多可以傳遞1000個左右的漢字。這樣認為其實是不對的,對於中文的傳 遞,最終會為urlencode後的編碼形式進行傳遞,如果瀏覽器的編碼為UTF8的話,一個漢字最終編碼後的字元長度為9個字元。(此段話引用URL最大長度問題,非常感謝)
所有樓主改用form提交,由於系統有多個頁面存在匯出檔案功能,並且一個頁面也存在匯出存在多個Excel的情況,故寫了個外掛程式,有啥意見和建議歡迎批評改正。
原始的方式:提前在介面先定義好form,當使用者點擊時提及。
//原生寫法<form method="POST" action="@Url.Action("ExportData", "Student")" id="exportForm"> <input type="hidden" id="studentName" name="studentName" /> <input type="hidden" id="birthDate" name="birthDate" /></form> //MVC封裝好的方法@Html.BeginForm("ExportData", "Student", FormMethod.Post, new { id = "exportForm" }) { <input type="hidden" id="stationCodes" name="stationCodes" /> <input type="hidden" id="studentName" name="studentName" /> <input type="hidden" id="birthDate" name="birthDate" /> }View Code
封裝好的外掛程式:
1 /* 匯出excel 2 11.13.2014 - LQZ - 全選網站url過長ie超過2083個字元將報錯,將所有url整合成form提交 3 */ 4 ;(function() { 5 var instance; 6 window.GridExportOperate = function () { 7 if (instance) { 8 return instance; 9 }10 instance = this;11 this.gridexport = function(formPara, formId, formUrl) {12 if (!$("#" + formId).length) {13 var form = document.createElement("form");14 form.type = "post";15 //form.style.display = "none";16 document.body.appendChild(form);17 form.action = formUrl;18 for (item in formPara)19 createInput(form, "hidden", item, formPara[item]);20 form.submit();21 } else {22 for (item in formPara)23 changeInput(item, formPara[item]);24 $("#" + formId).submit();25 }26 };27 28 function createInput(form, type, name, value) {29 var tmpInput = document.createElement("input");30 tmpInput.type = type;31 tmpInput.name = name;32 tmpInput.value = value;33 form.appendChild(tmpInput);34 }35 function changeInput(name, value) {36 $(‘#‘ + name).val(value);37 }38 };39 })(jQuery);View Code
調用方法建立類的執行個體後調用。
var gridxportOperate = new GridExportOperate();gridxportOperate.gridexport(formPara, formId, baseurl);
View Code
js代碼產生form,解決mvc的url參數過長問題