How to handle form events after adding a master page to an existing page

Here is a question that was asked on my posting trying to invite questions, Got a question- Get an answer here.

Question

Something that would be handy straight from the team is how to handle ASP.NET (2 and later) form events when a Master page is added after the fact.

Say for example a contact page with a button event to submit, but once a Master page is added the contact page lost it's form to the Master page.

Solution

So here is the page before we add a master page to it:

form

formcs

We just have a simple form which handles the click of the submit button.

So then I create a master page and add it by clicking on the MasterPageFile property in Visual Studio and selecting my master page:

addmaster

Now we have the master page added to the ASPX page.  We just have to update the HTML accordingly.  So we want to get rid of all the beginning information, including <html><body><form> tags and just have the tags of our content.  We then place that inside a ContentPlaceHolder tag that looks like:

 <asp:Content ID="Content2" Runat="Server" 
ContentPlaceHolderID="ContentPlaceHolder1">
...
</asp:Content>

We then remove our closing tags for those objects.  You want to make sure your ContentPlaceHolderID matches the placeholder on the master page you are trying to fill.  So my converted page now looks like:

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" MasterPageFile="~/Test.master" %>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div>
    
    <asp:Label ID="Label1" runat="server" Text="Email"></asp:Label>
&nbsp;&nbsp;&nbsp;
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />
    <br />
    First Name&nbsp;&nbsp;
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <br />
    Last Name&nbsp;&nbsp;
    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    <br />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
    </div>
</asp:Content>

The events themselves are handled just the same, in the originating page.  It is just the form tag that is in the master page.  So that is all we have to do.

kick it on DotNetKicks.com