Search code examples
javascriptasp.netvalidationwebformsviewstate

How to satisfy or bypass viewstate validation in Asp.net WebForms on separate post?


I`ve got a link in a Webforms page which opens in a new window, and posts to a form other than the page itself. This is done like this:

JS:

var submitFunc = function(){
    document.forms[0].action = 'http://urlToPostTo/somePage.aspx';  
    document.forms[0].target = '_blank'; 
    document.forms[0].submit();
}

The link:

<input type="hidden" id="myDataId" value="12345" />     
<a href="javascript:submitFunc();">Search</a>

As you can see, this overrides the target of the main <form>, and attempts to post to a different page. The whole point is that this should post/submit to a different page, while avoiding passing the data of "myDataId" as a Get parameter.

The above code would work, but causes an error due to viewstate validation.

Question: Is there any way for me to either satisfy the requirements here, or somehow bypass the viewstate validation so I can post my data this way?


Solution

  • Sounds like you just need to change the PostBackUrl of the button that submits the form.

    A simple example PostToPage1.aspx that posts to PostToPage2.aspx (instead of a postback):

    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="text1" runat="server" /><br />
        <asp:TextBox ID="text2" runat="server" />
        <asp:Button ID="btn1" runat="server" PostBackUrl="~/PostToPage2.aspx" />
    </div>
    </form>
    

    You can then inspect the Request in PostToPage2.aspx to check if it's a POST, etc. and then access the Request.Form collection in the Request in Page_Load.

    An overly simplified sample for PostToPage2.aspx (do add proper validation):

    if (!Page.IsPostBack && Request.RequestType == "POST")
        {
            if (Request.Form != null && Request.Form.Keys.Count > 0)
            {
               .....
    

    Hth...