I'm facing an issue where my Iframe response URL is replacing my parent(browser) URL instead of the opening inside the Iframe.
I have my Application page(default.aspx) page which I access from a browser. In that page, I loaded the iframe by passing 3 URL
./Response?Stauts=cancel
./Response?Status=Decline
./Response?Status=confirmed
Code snip of form posting to iFrame URL.
<%# Page Language="C#" %>
<script runat="server">
bool _postLoadCustom = false;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
string CANCELURL = Request.Params["CANCELURL"];
string ERRORURL = Request.Params["ERRORURL"];
string REDIRECTURL = Request.Params["REDIRECTURL"];
{
NameValueCollection data = new NameValueCollection();
data.Add("__CANCELURL", CANCELURL);
data.Add("__ERRORURL", ERRORURL);
data.Add("__REDIRECTURL", REDIRECTURL);
RedirectAndPOST(this.Page,"https://IframeURL/Content", data);
}
}
#region RedirectAndPost
public static void RedirectAndPOST(Page page, string destinationUrl,NameValueCollection data)
{
string strForm = PreparePOSTForm(destinationUrl, data);
page.Controls.Add(new LiteralControl(strForm));
}
private static String PreparePOSTForm(string url, NameValueCollection data)
{
string formID = "PostForm";
StringBuilder strForm = new StringBuilder();
strForm.Append("<form id=\"" + formID + "\" name=\"" +
formID + "\" action=\"" + url +
"\" method=\"POST\">");
foreach (string key in data)
{
strForm.Append("<input type=\"hidden\" name=\"" + key +
"\" value=\"" + data[key] + "\">");
}
strForm.Append("</form>");
//Build the JavaScript which will do the Posting operation.
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var v" + formID + " = document." +
formID + ";");
strScript.Append("v" + formID + ".submit();");
strScript.Append("<" + "/script>");
return strForm.ToString() + strScript.ToString();
}
#endregion
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
Loading...
</body>
</html>
As I complete the Iframe journey and click Submit(iframe button), I get the one of the URL which I passing to 3rd party service via Iframe. From this URL I extract the information(status). the URL I received in response should be redirected to Iframe but it is replacing my current URL(default.aspx).
Below code is my response page which i used to extract information from response URL and store into the session.
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
public void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
return;
}
else
{
string url = HttpContext.Current.Request.Url.AbsolutePath;
string status = Request.QueryString["status"].Split('-')[0];
string sessionID = Request.QueryString["status"].Split('-')[1];
string exampleServerUrl = ConfigurationManager.AppSettings["ServerURL"];
String sessionName = "ProductBase_1_0_0_0";
string request =
#"
<server><requests>
<resumeSession sessionID=""{0}""/>
<Session.setElementRq path=""data/policyAdmin/policynotes/FITSStatus"" value=""{1}""/>
</requests></server>";
request = string.Format(request, sessionID, status);
string response = this.HTTPPost(exampleServerUrl, request);
}
}
private string HTTPPost(string url, string requestXML)
{
string result = null;
System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
wr.Timeout = 90000;
wr.ServicePoint.ConnectionLimit = 10;
wr.Method = "POST";
wr.ContentType = "text/xml";
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(requestXML);
System.IO.Stream strm = wr.GetRequestStream();
strm.Write(byteArray, 0, byteArray.Length);
strm.Close();
System.Net.WebResponse resp = wr.GetResponse();
System.Text.Encoding enc = Encoding.GetEncoding("utf-8");
System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream(), enc);
result = reader.ReadToEnd();
reader.Close();
resp.Close();
return result;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="paypageresponce" runat="server" method="post">
<!--#include file="Response.html"-->
<label>Payment in progress...</label>
</form>
</body>
</html>
I include the Response.html page from which I have called the javascript function to click my Application button automatically.
I have intensively googled to get the solution but no luck. I tried to replace the iFrame URL but it was not allowed due to security by service.
I have debugged the code and reach to point as when I clicked the submit button of iframe, my response.aspx url replace my default.aspx.
Any one can let me know why response URL is replacing insted of redirected to IFrame.
Related
I have an ASP.NET Web forms site with C# code behind called from VS2013 running under Win 10 and viewed in Google Chrome. I am trying to call a C# function from Javascript in the Default.aspx markup as shown below
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<textarea id="txtPaste" placeholder="Paste Image Here" style="height: 100px;"></textarea>
<img id="imgPaste" src="C:\Users\Simon\Pictures\Download via Dropbox a.jpg"/>
<asp:Button Text="Save" runat="server" OnClick="Save" />
<input id="Text1" type="text" name ="ImageData" hidden="hidden" />
<script type="text/javascript">
window.onload = function () {
document.getElementById('txtPaste').focus();
document.getElementById('txtPaste').onpaste = function (event) {
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items));
var blob = null;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
if (blob !== null) {
var reader = new FileReader();
reader.onload = function (event) {
document.getElementById("imgPaste").src = event.target.result;
document.getElementById("Text1").value = event.target.result;
PageMethods.SaveImg(event.target.result.toString(), onSuccess, onFailure);
};
reader.readAsDataURL(blob);
}
}
};
function onSuccess(result) {
alert("Success! " + result);
}
function onFailure(result) {
alert("Failed! " + result);
}
</script>
</asp:Content>
The PageMethod is defined in Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.Services;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Save(object sender, EventArgs e)
{
string str = Request.Form["ImageData"];
SaveImg(str);
}
[WebMethod]
public static bool SaveImg(string str)
{
try
{
string imageData = str.Replace("data:image/png;base64,", "");
var bytes = Convert.FromBase64String(imageData);
string filePath = #"C:\Windows\Temp\File.jpg";
if (File.Exists(filePath)) File.Delete(filePath);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
return false;
}
catch (Exception Ex)
{
return true;
}
}
}
When I click in txtPaste and paste an image, the image appears in imgPaste OK and can be downloaded as a file by clicking by the Save button to execute the SaveImg function.
I am trying to create the file only by pasting an image, without clicking the Save button by defining SaveImg as Web Method and calling PageMethods.SaveImg after filling the Image control. The call to SaveImg shows and alert as specified in the OnSuccess function, but SaveImg is not executed - breakpoints set in the function are not hit on the Paste event, although they are if the Save button is clicked. The same behaviour is shown if the web site is viewed in Firefox.
ScriptManager in the Master.aspx file has EnablePageMethods set to True.
I have tried the following to make SaveImg execute on the paste event without success:
1) Commenting out settings.AutoredirectMode in Route.Config made PageMethods.SaveImg return a Fail status.
2) Commenting one or both lines in global.asax:
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
3) Using an AJAX function as shown below. sParam was defined as event.target.result.toString() and the call replaced the PageMethods.SaveImg call
function showDetail(sParam) {
$.ajax({
type: "POST",
url: "Default.aspx/SaveImg",
data: "{'str': '" +sParam +"'}", // passing the parameter
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(retValue) {
// Do something with the return value from.Net method
}
});
Calling a C# function from Javascript in ASP.Net can be done by placing the C# function in the click event of a control and then calling the control's click event from Javascript as shown below for the above scenario:
JavaScript in page markup:
%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<textarea id="txtPaste" name="txtPaste" placeholder="Paste Image Here" style="height: 100px;"></textarea>
<img id="imgPaste" src="C:\Users\Simon\Pictures\Download via Dropbox a.jpg"/>
<asp:Button Text="Save" runat="server" OnClick="cmdSave_Click" ID="cmdSave" />
<input id="Text1" type="hidden" name ="ImageData" hidden="hidden" />
<script type="text/javascript">
window.onload = function () {
document.getElementById('txtPaste').focus();
document.getElementById('txtPaste').onpaste = function (event) {
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items));
var blob = null;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
if (blob !== null) {
var reader = new FileReader();
reader.onload = function (event) {
document.getElementById("imgPaste").src = event.target.result;
document.getElementById("Text1").value = event.target.result;
//PageMethods.SaveImg(event.target.result.toString(), onSuccess, onFailure);
document.getElementById("txtPaste").value = "Image Pasted"
document.getElementById("cmdSave").click();
};
reader.readAsDataURL(blob);
}
}
};
</script>
C# code:
protected void cmdSave_Click(object sender, EventArgs e)
{
string str = Request.Form["ImageData"];
SaveImg(str);
}
public bool SaveImg(string str)
{
try
{
string imageData = str.Replace("data:image/png;base64,", "");
var bytes = Convert.FromBase64String(imageData);
string filePath = #"C:\Windows\Temp\File.jpg";
if (File.Exists(filePath)) File.Delete(filePath);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
imageFile.Write(bytes, 0, bytes.Length);
imageFile.Flush();
}
return false;
}
catch (Exception Ex)
{
return true;
}
}
Hi I'm trying to open hosted angular app to my application without using iFrame , Object and embed tags. Below is my Handler code. Css and js files are loaded properly but site is not working as expected.
**web.config app settings:**
<add key="ProxyMode" value="1"/>
<add key="RemoteWebSite" value="http://localhost/angulartest"/>
**Handler :**
public class ReverseProxy : IHttpHandler
{
private static string GetContentType(string url)
{
if (url.ToLower().Contains(".css"))
{
return "text/css";
}
else if (url.ToLower().Contains(".js"))
{
return "application/javascript";
}
else
{
return "text/html";
}
}
/// <summary>
/// Method calls when client request the server
/// </summary>
/// <param name="context">HTTP context for client</param>
public void ProcessRequest(HttpContext context)
{
//read values from configuration file
int proxyMode = Convert.ToInt32(ConfigurationSettings.AppSettings["ProxyMode"]);
string remoteWebSite = ConfigurationSettings.AppSettings["RemoteWebSite"];
string remoteUrl;
if (proxyMode == 0)
remoteUrl = ParseURL(context.Request.Url.AbsoluteUri); //all site accepted
else
remoteUrl = context.Request.Url.AbsoluteUri.Replace("http://" + context.Request.Url.Host + context.Request.ApplicationPath, remoteWebSite); //only one site accepted
//create the web request to get the remote stream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(remoteUrl);
//TODO : you can add your own credentials system
//request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (System.Net.WebException ex)
{
string dsdl;
using (var sr = new StreamReader(ex.Response.GetResponseStream()))
dsdl = sr.ReadToEnd();
//remote url not found, send 404 to client
context.Response.StatusCode = 404;
context.Response.StatusDescription = "Not Found";
context.Response.Write(dsdl);
context.Response.End();
return;
}
Stream receiveStream = response.GetResponseStream();
context.Response.ContentType = GetContentType(remoteUrl);
StreamReader readStream = new StreamReader(receiveStream, Encoding.Default);
Uri test = new Uri(remoteUrl);
string content;
if (proxyMode == 0)
content = ParseHtmlResponse(readStream.ReadToEnd(), context.Request.ApplicationPath + "/http//" + test.Host);
else
content = ParseHtmlResponse(readStream.ReadToEnd(), context.Request.ApplicationPath);
//write the updated HTML to the client
context.Response.Write(content);
//close streams
readStream.Close();
response.Close();
context.Response.End();
}
/// <summary>
/// Get the remote URL to call
/// </summary>
/// <param name="url">URL get by client</param>
/// <returns>Remote URL to return to the client</returns>
public string ParseURL(string url)
{
if (url.IndexOf("http/") >= 0)
{
string externalUrl = url.Substring(url.IndexOf("http/"));
return externalUrl.Replace("http/", "http://");
}
else
return url;
}
/// <summary>
/// Parse HTML response for update links and images sources
/// </summary>
/// <param name="html">HTML response</param>
/// <param name="appPath">Path of application for replacement</param>
/// <returns>HTML updated</returns>
public string ParseHtmlResponse(string html, string appPath)
{
html = html.Replace("\"/", "\"" + appPath + "/");
html = html.Replace("'/", "'" + appPath + "/");
html = html.Replace("=/", "=" + appPath + "/");
return html;
}
///
/// Specifies whether this instance is reusable by other Http requests
///
public bool IsReusable
{
get
{
return true;
}
}
}
Controller HTML is not firing. Attached Fiddler response also.
angulartest => Hosted angular application
ReverseProxy => My own application
Inbox.html not firing in my ReverseProxy project..
Please help me for this.
Finally I found the answer. Hosted application angular js relative path not taking during Reverse Proxy. So I added in CDN version of angular js in index.html,
Now it's working perfectly.
I have a fileupload control and a button in a webform.When i click on the button after selecting fileupload,it should save the image and rename it with a GUID.
protected void btnUpload_Click(object sender, EventArgs e)
{
string fileName = string.Empty;
string filePath = string.Empty;
string extension = string.Empty;
try
{
//Check if Fileupload control has file in it
if (FileUpload1.HasFile)
{
// Get selected image extension
extension = Path.GetExtension(FileUpload1.FileName).ToLower();
//Check image is of valid type or not
if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif" || extension == ".bmp")
{
//Cretae unique name for the file
fileName = Guid.NewGuid().ToString() + extension;
//Create path for the image to store
HiddenField1.Value = fileName;
filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
//Save image in folder
FileUpload1.SaveAs(filePath);
//Show the panel and load the uploaded image in image control.
//pnlCrop.Visible = true;
}
The above code works just fine,saves the image and passes the GUID to the hiddenfield.Now i want to pass the value of hiddenfield to a client side variable and then display it as an alert.
<script type="text/javascript">
function showfilename() {
setTimeout(function () {
var dpGUID = document.getElementById('<%= HiddenField1.ClientID %>').value;
alert(dpGUID);
},3000)
}
</script>
Reason for using timeout? Because i want to read value of hiddenfield after it has been assigned the value on button click.
Note:I am using two functions on Buttonclick.One on client side and other on server side as follows :
<asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Button" OnClientClick="showfilename()" />
Is it possible? If yes,what could be causing a problem?
Try using a RegisterClientScriptBlock
protected void btnUpload_Click(object sender, EventArgs e)
{
/*All your code here*/
//instead of HiddenField1.Value = fileName; write the line below
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "callJsFunction", "alert('" + fileName + "');", true);
}
and now you can get rid of the OnClientClick="showfilename() and the HiddenField
I'm a novice with webservices, so this one has me stumped. I have created a webservice that will (eventually) accept a block of html and create a pdf file from it. To keep it simple, currently I'm not passing any parameters into the service; I'm just creating a pdf document with "hello world" in it. In debug mode, when I call the service directly (i.e. start debugging from that asmx page), I can invoke the exportPDF() method and the results are perfect -- it creates the pdf just as I'd hoped.
The problem is when I call the webservice from a javascript, nothing happens. I've set up a breakpoint inside the service, so I know it's getting called, and as I mentioned there are no parameters being passed in, so I don't understand why it works when it's invoked directly, but not when it's invoked from a javascript call.
My javascript and webservice code is below...any help would be greatly, greatly appreciated!!
Javascript:
function getPDF(elem) {
var param = { html: elem.innerHTML };
$.ajax({
type: "POST",
contentType: "application/json; charset=UTF-8",
url: "../WebServices/exporting.asmx/exportPDF",
data: "{ }",
dataType: "json",
success: function (response) {
}
})
}
WebService:
using DMC.Classes;
using NReco.PdfGenerator;
using System;
using System.IO;
using System.Web;
using System.Web.Services;
using System.Web.UI;
namespace DMC.WebServices
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class exporting : System.Web.Services.WebService
{
[WebMethod]
public void exportPDF()
{
WriteDocument("htmlToPDF.pdf", "application/pdf", ConvertHtmlToPDF());
}
public byte[] ConvertHtmlToPDF()
{
HtmlToPdfConverter nRecohtmltoPdfObj = new HtmlToPdfConverter();
nRecohtmltoPdfObj.Orientation = PageOrientation.Portrait;
nRecohtmltoPdfObj.PageFooterHtml = CreatePDFFooter();
nRecohtmltoPdfObj.CustomWkHtmlArgs = "--margin-top 35 --header-spacing 0 --margin-left 0 --margin-right 0";
return nRecohtmltoPdfObj.GeneratePdf(CreatePDFScript() + "Hello world" + "</body></html>");
}
public string CreatePDFScript()
{
return "<html><head><style>td,th{line-height:20px;} tr { page-break-inside: avoid }</style><script>function subst() {var vars={};var x=document.location.search.substring(1).split('&');for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}" +
"var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];for(var i in x) {var y = document.getElementsByClassName(x[i]);" +
"for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];}}</script></head><body onload=\"subst()\">";
}
public string CreatePDFFooter()
{
return "<div style='text-align:center;font-family:Tahoma; font-size:9px;'>Page <span class=\"page\"></span> of <span class=\"topage\"></span></div>";
}
public void WriteDocument(string fileName, string contentType, byte[] content)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
HttpContext.Current.Response.CacheControl = "No-cache";
HttpContext.Current.Response.BinaryWrite(content);
HttpContext.Current.Response.Flush();
}
}
}
Thanks for the response, Mason! I've been working on this and found a solution; and while I admit it's not perfect, I don't think it's too bad. From all the different material I read, I started to get the feeling that a web service is more of a "go between" for passing data and not really meant to handle functionality like posting PDF documents. It would let you get away with it when debugging and invoking it directly, but that's about it.
So instead of using a web service, I created a class object. I also created a hidden field in my html. This field gets populated with the desired div.innerHtml content via JavaScript when somebody clicks the "Export to PDF" button. Upon postback, my codebehind checks to see if the hidden field is empty and if it isn't, it calls the exportPDF function, which in turn instantiates the class object that creates/downloads the PDF. The biggest pitfall to doing it this way, and some may consider this a big pitfall, is that to read in a field in the codebehind that has html markup in it you have to turn off validation for the web page, which obviously opens up your code for malicious attacks.
Below are the highlights of my code:
Web.Config
Add requestValidationMode = "2.0" to the web.config file
<system.web>
<httpRuntime
requestValidationMode="2.0"
targetFramework="4.5"
/>
</system.web>
.aspx Page:
Set ValidateRequest="false" in Page reference
<%# Page Title="Referrals" Language="C#" MasterPageFile="~/Behavior/Behavior.master" AutoEventWireup="true" CodeBehind="Referrals.aspx.cs"
Inherits="DMC.Behavior.Referrals" ClientIDMode="Static" EnableEventValidation="false" ValidateRequest="false" %>
.
.
.
<asp:LinkButton ID="LinkButton2" runat="server" OnClientClick="createPDF();">
<img src='../Images/icons/pdf.png'>PDF</asp:LinkButton>
.
.
.
<div id="export_pdf" class="pdfWidth_Portrait pdfSection" style="margin-top: 10px;" runat="server">
<div class="alert-info text-center" style="margin: 0; padding: 0;">
<table class="table table-condensed" style="margin-top: 0; padding: 30px; width: 100%;">
.
.
.
</table>
</div>
</div>
.
.
.
<asp:HiddenField ID="pdfData" runat="server" />
.
.
.
<script type="text/javascript">
function createPDF() {
document.getElementById("pdfData").value = document.getElementById("export_pdf").innerHTML;
}
</script>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Set the hidden pdf field to null initially
pdfData.Value = "";
}
//If this field is no longer null, it means somebody is wanting to export into PDF
if (pdfData.Value != "")
{
exportPDF();
}
}
public void exportPDF()
{
string fileName = null;
export dmc = new export();
fileName = lblLocation.Text + " Behavior Statistics YTD " + lblDate.Text;
dmc.exportPDF(fileName, "Portrait", pdfData.Value);
//PDF downloaded, reset value to ""
pdfData.Value = "";
}
Export Class
using NReco.PdfGenerator;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace DMC.Classes
{
public class export
{
public void exportPDF(string fileName, string Orientation, string html)
{
HtmlToPdfConverter pdf = new HtmlToPdfConverter();
//Remove these control characters, they interfere with the formatting of the pdf document
html = html.Replace("\n", "");
html = html.Replace("\t", "");
html = html.Replace("\r", "");
switch (Orientation)
{
case "Portrait":
pdf.Orientation = PageOrientation.Portrait;
break;
case "Landscape":
pdf.Orientation = PageOrientation.Landscape;
break;
default:
pdf.Orientation = PageOrientation.Default;
break;
}
//In case needed for future
//pdf.CustomWkHtmlArgs = "--margin-top 35 --header-spacing 0 --margin-left 0 --margin-right 0";
pdf.Margins.Top = 25;
pdf.PageFooterHtml = createPDFFooter();
var pdfBytes = pdf.GeneratePdf(createPDFScript() + html + "</body></html>");
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".pdf");
HttpContext.Current.Response.BinaryWrite(pdfBytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
private string createPDFScript()
{
return "<html><head><style>td,th{line-height:20px;} tr { page-break-inside: avoid }</style><script>function subst() {var vars={};var x=document.location.search.substring(1).split('&');for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}" +
"var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];for(var i in x) {var y = document.getElementsByClassName(x[i]);" +
"for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];}}</script></head><body onload=\"subst()\">";
}
private string createPDFFooter()
{
return "<div><table style='font-family:Tahoma; font-size:9px; width:100%'><tr><td style='text-align:left'>Research Dept|RR:mm:jpg</td><td style='text-align:right'>Page <span class=\"page\"></span> of <span class=\"topage\"></span></td></div>";
}
}
}
ClientScript.RegisterStartupScript(this.GetType(), "load", "HideProgress
();window.location.href='DownloadFile.ashx';", true);
Handler file:
public class DownloadFile : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public void ProcessRequest (HttpContext context) {
if (context.Session["fileContent"] != null && context.Session["filename"] != null)
{
//Download the excel file
System.IO.StringWriter fileContent = (System.IO.StringWriter)context.Session["fileContent"];
string filename = context.Session["filename"].ToString();
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.ClearContent();
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
context.Response.Write(fileContent.ToString());
context.Response.Flush();
}
}
Textbox with calender control does showing calender image in IE after file download.
Make sure you have DOCTYPE declared
<!DOCTYPE html>
along with user agent indicator to tell IE to use the latest rendering engine available
<meta http-equiv="X-UA-Compatible" content="IE=edge">