Tip #87: Did you know… How to reuse a web page by converting into an ASP.NET User Control?


If you want to reuse a web form’s content in other places in your application, you can easily convert the page into an ASP.NET User Control. Then you can add that user control to any other page.

For example, you have a page in your application that looks like the following:

WebForm

 

Now, you need to rename to the file to have a .ascx extension. Then remove html, head, body, form tags from the page. Change the "@ Page" directive to a "@ Control" directive.  Remove all attributes of the "@ Control" directive, except Language, AutoEventWireup, CodeFile, and Inherits. You also need the change the Inherits to have your new UserControl code behind file’s name, like in the image below. Close and re-open the file to make squiggles go away.

MyUserControl 

 

If you have a code-behind file, its name will be changed properly for you automatically. Open the file and change the class it inherits from to UserControl, and the class name to match your .ascx file. See below.

MyUserControlCodeBehind

More information can be found here.

Comments (4)

  1. Funny this is also an .NET exame question 🙂

  2. dahlbyk says:

    You would also want to remove the DOCTYPE.

  3. L says:

    It would be easier to create the user control and copy the content into it.

  4. karma says:

    I think it would be easier to create new user control and then paste the content of the page to the new control.

    and then delete the page.