Using C# Web Forms, I am attempting to use hidden fields as part of a redirect from website A to website B (same domain, both sites password protected using Forms Authentication). I have tried different approaches, but so far am unable to extract the hidden field values from the Request.Form NameValueCollection in the website B Login code-behind, and am getting a null reference exception when trying to access the request form key.
Website A:
<asp:LinkButton ID="redirectLink" runat="server" OnClick="RedirectLink_Click"
OnClientClick="window.document.forms[0].target='_blank';">New Page - Website B
</asp:LinkButton>
Response.Clear();
StringBuilder sb = new StringBuilder();
sb.Append("<html>");
sb.Append("<body onload='submitForm()'>");
sb.AppendFormat("<form id='customForm' action='{0}' method='post'>", url + "/newpage.aspx?redirectPage=NewPage_Redirect");
sb.AppendFormat("<input type='hidden' name='Val1' value='{0}' id='Val1'>", Uri.EscapeDataString(value1));
sb.AppendFormat("<input type='hidden' name='Val2' value='{0}' id='Val2'>", Uri.EscapeDataString(value2));
sb.Append("</form>");
sb.Append("<script>");
sb.Append("function submitForm() {");
sb.Append("document.getElementById('customForm').submit();");
sb.Append("}");
sb.Append("</script>");
sb.Append("</body>");
sb.Append("</html>");
Response.Write(sb.ToString());
HttpContext.Current.ApplicationInstance.CompleteRequest();
Website B Page_Load:
if ((Request.QueryString["redirectPage"] != null)
&& (Request.QueryString["redirectPage"].ToString() == "NewPage_Redirect"))
{
Response.Write(Request.Form["Val1"].ToString()); // NULL REFERENCE EXCEPTION
Response.Write(Request.Form["Val2"].ToString());
}
What am I missing?
UPDATE 1
Website A:
This is the HTML I see in VS 2022:
<html>
<body onload='submitForm()'>
<form id='customForm' action='https://websiteB.com/newpage.aspx?redirectPage=NewPage_Redirect' method='post'>
<input type='hidden' name='Val1' value='abc123' id='Val1'>
<input type='hidden' name='Val2' value='def456' id='Val2'>
</form>
<script>
function submitForm()
{
document.getElementById('customForm').submit();
}
</script>
</body>
</html>
Website B Page_Load:
When I changed Response.Write(Request.Form["Val1"].ToString()) on website B to Response.Write(Request.Form["Val1"]), I no longer got the null reference exception. So, I replaced the test code on website B with the following which displays 0 for the length of keys:
string[] keys = Request.Form.AllKeys;
Response.Write(keys.Length.ToString()); //Displays 0
UPDATE 2:
Using browser tools, it seems the HTML being created in code is not appearing in the generated HTML. I'm starting to suspect this may be like an issue I dealt with 12 years ago, where ASP.NET Web Forms does not allow nested forms. Still investigating.
UPDATE 3
I forgot to mention I'm using a LinkButton on the ASPX page - code snippet above has been updated.