Improved 'Hello World'

In the introductory task, you added some text, a textbox, a button and a literal to an ASP.Net page, the page should have worked, but there are a number of issue with the page which we would want to avoid in a professional setting:

Follow the steps below to create an improved version of the web form

  1. Create a new aspx page (web form) as before, and create a welcome <h1> element
  2. Drag a Label onto the page and set it's text to be 'What is your name?'
  3. In the properties section for the label change its 'id' property to lblName
  4. Add a TextBox to the page, and set its id to txtName
  5. Return to the label, and set its AssociatedControlId property to txtName.

    This will ensure that when the page is rendered as HTML, the label is associated with the text box

  6. Add a button to the next line, and change its id property to btnProcessGreeting, and set its text to 'Submit'
  7. Add a literal on the next line, and change its id property to litGreeting
  8. You should now have a page with four interactive elements: lblName, txtName, btnProcessGreeting and litGreeting
  9. As we have worked in design view, Visual Studio will have added some unwanted elements (for example, it may have separated content with the <br> tag). Clean up the code, and if you wish to separate elements on the page, do so using div tags.
  10. You should end up with code similar to that shown here
    <asp:Label ID="lblName" runat="server" Text="What is your name?"  AssociatedControlID="txtName"></asp:Label>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <asp:Button ID="btnProcessGreeting" runat="server" Text="Submit" />
    <asp:Literal ID="litGreeting" runat="server"></asp:Literal>
  11. Double click on the button, this will take you into the C# 'code behind' for the page
  12. You should see an empty method called btnProcessGreeting_Click. It is named based on the name of the button.
  13. In the blank line between the braces add code as shown:
    protected void btnProcessGreeting_Click(object sender, EventArgs e)
        litGreeting.Text = "<p>Hello " + txtName.Text + "</p>";

    The code should be much easier to understand than in the introductory task

  14. Save the page and run the application, it should look similar to before, it will function as before, but if you view the source code of the website, you will see that the label is 'for' the textbox as shown here:
    <label for="txtName" id="lblName">What is your name</label>
    <input name="txtName" type="text" id="txtName" />
This tutorial is a slightly modified version of one originally found at Scotty's Tutorials