HttpContext modification breaks SharePoint Site





5.00/5 (1 vote)
Modifying HttpContext context-disposition in a WebPart will break SharePoint Response
Often it is required to return a file from a web-part
OnSubmit()
. The standard practise is:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}",_ExcelFile
));
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.ContentType = "application/ms-excel";
However, once the user clicks on the Submit, the SharePoint Site will stop responding. Now there are ways to fix this, either you do a Server Redirect and create a new HttpContext
or just add the following line to your Button
:
btnSubmit.OnClientClick = "this.form.onsubmit = function() {return true;}";So in your WebPart
btnSubmit_OnClick()
,
private void btnSubmit_Click(object sender, EventArgs e) { if (IsEditMode) return; EnsureChildControls(); System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); try { if (dtStartDate.IsDateEmpty || dtEndDate.IsDateEmpty) return; String strCashType = ddCashType.Text; String strTType = ddTransactionType.Text; String xlsFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; if (ExcelFile == null || ExcelFile == " ") _ExcelFile = "Export" + xlsFileName; else _ExcelFile += xlsFileName; // HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}",_ExcelFile)); HttpContext.Current.Response.Charset = " "; HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); HttpContext.Current.Response.ContentType = "application/ms-excel"; // DataGrid dgTemp = new DataGrid(); dgTemp.DataSource = oSycoDB.getSycoData(dtStartDate.SelectedDate.ToString("yyyy-MM-dd"), dtEndDate.SelectedDate.ToString("yyyy-MM-dd"), strCashType, strTType); dgTemp.DataBind(); dgTemp.RenderControl(oHtmlTextWriter); HttpContext.Current.Response.Write(oStringWriter.ToString()); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } catch (Exception ex) { // HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Error.txt"); HttpContext.Current.Response.Charset = " "; HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); HttpContext.Current.Response.ContentType = "text/plain"; oHtmlTextWriter.Write(ex.Message+"\n"+ex.StackTrace); HttpContext.Current.Response.Write(oStringWriter.ToString()); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); // SingleJunket.LogMessage(ex.Message, EventLogEntryType.Error,1002, 1); } }Enjoy coding.