Create a New ASPX Page On Button Click in ASP.NET

Note - I am using a simple Text box but you can use a html text box which available at many sites for free. But concept is same.

Step 1: Take a textbox,button,and a link to check created page.

<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: Add given namespace

using System.IO;

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 page..add some text to your text box and click on button.. Then hit on hyperlink to show page.

Note - If you add html tags in your textbox then you have to add given tag into your web.config file.

Replace <page> by   <pages validateRequest="false"> if already exist otherwise add it between <system.web> tabgs

if you are use simple text in textbox then no need to add above tags

Ebook Download
View all
Learn
View all