Avoiding having to go back twice after writing html with an onload=document.form.submit() to HttpContext.Current.Response

Go To StackoverFlow.com

3

So that's a long title, here's what I'm doing: To avoid having report parameters show up in the URL I'm doing this in a button click handler in the code-behind to show the report:

System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write("<html><head></head>");    
System.Web.HttpContext.Current.Response.Write("<body onload=\"document.mainform.submit(); \">");
System.Web.HttpContext.Current.Response.Write(string.Format(CultureInfo.InvariantCulture, "<form name=\"mainform\" method=\"post\" action=\"{0}\">", ReportURL));
foreach (string key in Params.Keys)
{
    System.Web.HttpContext.Current.Response.Write(string.Format(CultureInfo.InvariantCulture, "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", key, Params[key]));
}
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body></html>");

This works great, but when I go back from the report I'm taken to the page I just generated which immediately submits the form due to the onload event. I can hit back twice really quickly to go back past it but this isn't ideal.

I've tried opening a new window with JavaScript using ClientScript.RegisterStartupScript before writing the html but I don't know how (or if it's even possible) to get the HttpContext for the new window.

2012-04-04 23:05
by Mike B


0

I ended up opening a new window. I added two small javascript functions

function openNewWin() {
    $('form').attr('target', '_blank');
    setTimeout('resetFormTarget()', 500);
}

function resetFormTarget() {
    $('form').attr('target', '');
}

Then in the linkbutton I set

OnClientClick="openNewWin();"

The OnClick still executes the code above server-side but the response is written to the new window. The setTimeout in the openNewWin function resets the form's target property so the app will still function normally after coming back to it.

2012-06-15 00:22
by Mike B


0

I wasn't able to recreate the problem using your code, so more context may help. Depending on how the rest of the page is structured, you may be able to use PostbackURL instead of a click handler:

<form id="form1" runat="server">
    <asp:HiddenField runat="server" ID="Key1" Value="Value1"/>
    <asp:HiddenField runat="server" ID="Key2" Value="Value2"/>
    <asp:Button runat="server" ID="button"
        Text="ok" PostBackUrl="ReportURL.aspx"/>
</form>

This way you don't have to worry about an extra/replaced page in the browser history.

2012-04-06 18:29
by mcknz
Thanks, but I need the click handler because the report parameters are created dynamically based on some page content - Mike B 2012-04-09 18:29
I would think there's a more direct way to do this -- writing out a form that submits itself seems like more of a workaround. Maybe post more of your code - mcknz 2012-04-10 14:56
Ads