Share via


Tip: change response querystring for the postback on the server-side

How do you change the response querystring for the postback? We know that it was very difficult to change the response action in v1, and this feature was just added in v2 using cross page posting, but how about change the querystring dynamically? You would think it should be very easy given that the form action is practically unchanged, turns out this is not easy in v1. You would either have to change the form action using client side code or use your own custom HtmlTextWriter to emit different form action.

 

In v2, this just became a lot simpler by using cross page posting. There is based on an important behavior in cross-page posting – if the postbackurl points back to the original page, this is simply treated as regular post back, instead of cross-page posting. Therefore you can simply set the postbackurl back to the current page with the querystring you need. For example,

 

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<script runat="server">

    private String queryString;

   

    protected void Page_PreRender(object sender, EventArgs e) {

        if (!String.IsNullOrEmpty(queryString)) {

            Button1.PostBackUrl = queryString;

        }

    }

 

    protected void Page_Load(object sender, EventArgs e) {

        queryString = "?foo=bar;a=b";

    }

</script>

 

<html xmlns="https://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Change Response QueryString</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:Button ID="Button1" runat="server" Text="PostBackWithQueryString" />

    </div>

    </form>

</body>

</html>