Adding a new .aspx page is the process of creating a new file and adding correct HTML to the page. Depending on the ASP.NET version, you may have to check and change the default HTML in the page.
Create a basic ASP.NET Web Application in Visual Studio. On the default form, we will create three controls, a TextBox, a Button, and a Hyperlink. On the Button click event handler, we will create a new page and on the hyperlink, we will navigate to the newly created page. The text content will be written in the new page. The new page name is text.aspx.
Step 1: Add three control to the default Web Form.
- <asp:TextBox ID="TextBox1" runat="server" Height="286px" TextMode="MultiLine" Width="285px"></asp:TextBox>
- <asp:Button ID="Button1" runat="server" Text="create new page at runtime" OnClick="Button1_Click" />
- <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/test.aspx">check it</asp:HyperLink>
Step 2: In the code behind, import the following namespace.
using System.IO;
We're going to use some file related classes that are defined in this namespace.
And write this code to your button click event.
- string str1 = @"<%@ Page Language=""C#"" %><script runat=""server""></script><html><head runat=""server""><title></title></head><body> <form id=""form1"" runat=""server""> <div>";
- string str2 = @"</div></form></body></html>";
- string str3 = FreeTextBox1.Text;
- string pagestring = str1.ToString() + str3.ToString() + str2.ToString();
- string fileLoc = Server.MapPath("~/test.aspx");
- FileStream fs = null;
- if (!File.Exists(fileLoc))
- {
- using (fs = File.Create(fileLoc))
- {
- using (fs = File.Create(fileLoc))
- {
- }
- }
- if (File.Exists(fileLoc))
- {
- using (StreamWriter sw = new StreamWriter(fileLoc))
- {
- sw.Write(pagestring.ToString());
- }
- }
Step 3: Run your application. Enter some text in the TextBox and click on the button. Then hit on hyperlink to navigate to the new page.
This tip is an idea how you can create your own .aspx pages. The trick is, depending on the ASP.NET version, each page will have something different in its HTML. To create the correct version of aspx page, you must copy the content of a detault page and add to the HTML in the above code.
Basically, what you're doing is, actually create HTML dynamically.
Hope it helps!