I came across this on a recent .NET web development project. The problem? How to pass variables from one form to another. In my case, I was landing on a page to create or edit a record. I needed the page to sometimes be passed a record id which it could load. Likewise, if I created a new record with this page and then reloaded the page, I needed to pass the new record’s id. This is pretty common functionality and is handled in most server-side languages (standard ASP, PHP, etc.) with querystrings since they can be dynamically generated. ASP.NET isn’t intended to use querystrings with form elements. In fact, if the form is set as runat=server, then .NET will ignore the querystring portion if you try to use it in the .aspx file, like this:
<form id="Form1" runat="server" action="=default.aspx?item_id<%=itemID%>">
The above won’t work. This is related to ASP.NET’s goal of being an event driven model, just like developing Windows applications. At first I thought I’d be able to change the querystring via code-behind, but, again, that’s not how things work, as shown in this article: PRB: Cannot Change or Remove the QueryString Action for a Web Form on Postback
Microsoft’s recommended solution is to store the data you want the next page to access (even if it’s the same page) as public properties of the page’s code-behind class. Then, call the page using Server.Transfer. Since this method passes control from one page to another without a round trip to the browser, the second page can still access data on the first page. Passing information between pages - The .NET way
So, what am I complaining about? Well, first, this isn’t the best technique in the world. For one thing, the receiving page has to have explicit knowledge of the calling page. But the real problem was when I got errors using Server.Transfer. Here’s the KB article. PRB: “Error Executing Child Request” Error Message When You Use Server.Transfer or Server.Execute in ASP.NET Page
Notice the workaround? “Use Response.Redirect.” Which means a server round trip. Which means no access to the previous form’s variables.
So, I’m back to square one. :-)
Now, I suppose I could have figured out why the error was occurring and fixed it, but who has time when you’re given a few days to go live by crazy clients? (You know who you are.) So, I did the blechy, ucky soup of the nightmarish coding soul thing. I put the data into session variables. It wasn’t much, and got the job done.
(note1: I think that .NET 2.0 and Visual Studio .NET 2005 can dynamically change a form’s query string. Not sure.)
(note2: Of course, I’m not at all an expert on .NET, and I’ll bet there’s something fundamental I don’t know that I should. So there, I’ve admitted it.)