ASP.NET Web Applications - part one
Posted By R Freeman on 02-Oct 2010 at 16:55
Musings from the basement of a very tall building
From visual studio 2010 select a new project and choose a VisualC#/Web/ASP.NET empty web application project. The machine will have clunk while it sets up the project for you. Next in the solution explorer right click the project and choose Add/New Item, select a web form. More clunking and the web form will appear in the solution explorer with two more files nested beneath it. If you run the project it will fire up a local web server and give you a blank web page. Excellent.
First the good news. You need have nothing to do with the webform1.aspx.designer.cs. In this blog I will ignore webform1.aspx.cs also.
Look at the webform1.aspx file and you will see it has a line of asp code at the top, and the rest is bog standard html. Note how it has an html form in the body with this unusual term runat="server" rather than the usual stuff telling it which page to send itself to. You can write html within the form, so lets assume we are making a patient index and want to collect Hospital Identifier, Forename, Surname, Birthdate, Gender, and to keep it politically correct NHS Number. I know your itching to use a fancy interface for all this but in the interest of simplicity use a 2 column html table for layout. Put a label (Forename:, etc.), in the left column, and text boxes (input type="text" name="txtForename", etc.) for the data, in the right column. In the bottom row of the table place a submit button (input type="submit" value="Submit"). The name for the textboxes is essential, is the name part of the http name value pair. Note that I left the tags out because I don't want the blog to think I'm injecting html.
Run the project and the form should appear in the browser. Right click and look at the source. It is as you would expect, except that the ASP engine the code has gone through has filled the html form construct out properly with a method of post (as per a form submit) but unusually the action is the same page -ie- it posts to itself; ouch. Secondly an input type="hidden" called _viewstate has been added whose value is incomprehensible.
Start up your trusty copy of Fiddler, put some values in your form, and click the submit button. The _viewstate and its value, along with your textbox names and their values (-ie- their content) have been posted to webform1.aspx. As you have done nothing with this, the web server has dutifully sent you a new instance of webform1.aspx back, giving the appearance of reseting your form. Really unhelpful, but nothing NHS workers are unused too.
Next time we will put some c# code in webform1.aspx.cs to stop it resetting the form, and to pick the form values up. In the true tradition of the thriller the achilles heel nature of the _viewstate will be revealed as well.