<asp:Panel ID="pnlSearch" runat="server" DefaultButton="btnValidateName">
<div class="spPad">
<b class="userLabel">Enter Full/Partial First or Last Name to Search (Leave blank for all):</b>
</div>
<div class="spPad" style="text-align: right;">
<asp:TextBox ID="txtName" Width="95%" runat="server" ClientIDMode="Static"></asp:TextBox>
</div>
<div class="spPad" style="text-align: right;">
<asp:Button ID="btnValidateName" CssClass="orange button" runat="server" Text="Validate Name" onclick="btnValidateName_Click" />
</div>
<div class="spPad" style="text-align: right;">
<asp:Label runat="server" Text="" ID="lblIsValid"></asp:Label>
</div>
</asp:Panel>
在转发器中搜索并显示结果后,我允许用户通过点击链接按钮打开一个新窗口来浏览浏览器中的文件:
<asp:LinkButton ID="lnkView" Text="View in Browser" OnClientClick="window.document.forms[0].target='blank';" runat="server" OnClick="ViewFile" />
背后的代码是:
protected void ViewFile(object sender, EventArgs e)
{
Response.Redirect("OpenFilePDF.ashx?fileVar=" + Session["fileName"]);
}
OpenFilePDF.ashx
代码为:
public void ProcessRequest (HttpContext context) {
System.Web.HttpRequest request2 = System.Web.HttpContext.Current.Request;
string strSessVar2 = request2.QueryString["fileVar"];
try
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/pdf";
byte[] fileByteArray = File.ReadAllBytes(Path.Combine(@"C:\PDF", strSessVar2));
response.AddHeader("Content-disposition", String.Format("inline; filename={0}", strSessVar2));
response.BinaryWrite(fileByteArray);
response.End();
}
catch (Exception ce)
{
}
}
public bool IsReusable {
get {
return false;
}
}
正在发生的情况是,在搜索并显示结果后,如果用户点击View in Browser
按钮并返回到旧窗口并点击Validate Name
按钮,结果就会发生在最初打开的窗口中,单击View in Browser
按钮而不是在当前窗口上运行搜索。我必须刷新页面才能再次搜索当前窗口,即使新窗口已经打开。
如何解决我遇到的问题?
答案 0 :(得分:2)
您的View in Browser
已实施为
<asp:LinkButton ID="lnkView" Text="View in Browser" OnClientClick="window.document.forms[0].target='blank';" runat="server" OnClick="ViewFile" />
在客户端点击上,您网页的表单元素将如下所示
<form ... target="_blank">
导致表单的任何提交在新窗口中打开。但是,每次回发到ASP.NET都构成了表单的提交,因此所有内容都将在新窗口中打开。您可以考虑在链接上设置属性,而不是在表单上设置target
属性。为此,请参阅以下答案:
https://stackoverflow.com/a/2637208/1981387
请注意,您必须使用HyperLink
而不是LinkButton
。实际上,通过将往返服务器的往返减少1,这将使您受益,因为您正在使用LinkButton
重定向到另一个URL。因此,HyperLink
href
可能只有一个"OpenFilePDF.ashx?fileVar=" + Session["fileName"]
,指向<asp:LinkButton ID="lnkView" Text="View in Browser" OnClientClick="window.document.forms[0].target='blank';" runat="server" OnClick="ViewFile" />
。
修改/ TL; DR:强>
更改
public string FileLocation
{
get
{
return "OpenFilePDF.ashx?fileVar=" + Session["fileName"];
}
}
protected void Page_Load(object sender, EventArgs e)
{
...
lnkViewProper.NavigateUrl = FileLocation;
...
}
要
代码隐藏:
<asp:HyperLink
ID="lnkViewProper"
Text="View in Browser"
runat="server"
Target="_blank" />
标记:
{{1}}