views:

76

answers:

2

I have a set of screens in C#/ASP where the user enters information. It's broken up into multiple parts to make it more user friendly. It used to be in separate pages, but that was very difficult to manage, as all the info is very related. So it was changed to be panels in one page that we show and hide based on the user's progress.

We want to be able to move things around pretty easily. Currently we have to do a lot of copy-pasting which isn't particularly quick plus it's error prone. Is there a better way to handle multi-part forms that makes them more modular?

(As background, I'm mostly a Java Developer, who's recently been working with .NET)

+3  A: 

An .ascx file, also known as a UserControl is a good way reusing common html / code behind throughout a project. They're essentially just a container for other .NET controls.

So let's pretend you have a very simple form where you're just asking for a person's name and age, and for some reason you want this used many times in a page or on several pages...

UserControl1.ascx

markup:

    <asp:Label runat="server" id="lblName" Text="What is the person's name?" AssociatedControlID="txtName"></asp:Label>
    <asp:TextBox runat="server" id="txtName"></asp:TextBox>
    <asp:Label runat="server" id="lblAge" Text="What is the person's age?" AssociatedControlID="txtAge"></asp:Label>
    <asp:TextBox runat="server" id="txtAge"></asp:TextBox>

<asp:Button runat="server" id="btnSubmit" Text="Submit" Onclick="btnSubmit_Click"></asp:Button>

code behind:

private Person _Person;

protected void btnSubmit_Clicked(object sender, EventArgs args)
{
  _Person = new Person() { Name = txtName.Text, Age = txtAge.Text };
}

public Person GetPerson()
{
   return _Person;
}

Then on some other page you just drop this user control in, and you can reference it like this:

Default.aspx

markup:

<%@ Register src="UserControl1.ascx" tagname="UserControl1" tagprefix="uc1" %>
<html>
...blah blah...
<p>Tell us about you</p>
<uc1:UserControl1 ID="ucYou" runat="server" />
<p>Tell us about your friend</p>
<uc1:UserControl1 ID="ucYourFriend" runat="server" />
.. blah blah
</html>

code behind:

 protected void SomeMethodThatSavesPage()
 {
    // other stuff
    Person you = ucYou.GetPerson();
    Person yourFriend = ucYourFriend.GetPerson();
 }

Page Directive

As Robert reminded me in the comments, you need to make sure the page using the UserControl has the correct page directive at the top. If you are in design view and just drag the UserControl onto the page, Visual Studio will handle this for you. Otherwise, you need to include it yourself.

Kirschstein
Make sure you register the tag prefix uc1.
Robert Harvey
@Robert: Forgot about that! added now.
Kirschstein
+1 Good post...
Robert Harvey
A: 

You might want to check out the wizard control--it is designed to handle exactly this scenario.

Wyatt Barnett