Generating HTML file which fetch data from SQL in the C# and ASP.NET
I'm new to ASP.NET and now I am creating an HTML file in ASP.NET C# which is stored in an folder. Now when the aspx file is run it will fetch some data and display it in the output. And there is an button. When I click it the HTML file is created.
Now my problem is I want to fetch the same data in the HTML file also to display it and to save it.
I'm creating the HTML file using StreamWriter and writeline in the code-behind. Or is there any other way to convert that aspx output file into an HTML file and save it in the same folder of the project?
protected void Button1_Click(object sender, EventArgs e)
{
string thisdir = Server.MapPath("./New Folder/SalesContract.htm");
StreamWriter 开发者_如何学编程sw = new StreamWriter(thisdir, true);
sw.WriteLine("<html>");
sw.WriteLine("<head>");
sw.WriteLine("<title> Sales Invoice</title>");
.............
sw.WriteLine("<b> <label for=lb_seller1 value=" + ds.Tables[0].Rows[0]["po_seller_Name"].ToString() + "/></b><br/>");
........
sw.WriteLine("</body>");
sw.WriteLine("</html>");
sw.Flush();
sw.Close()
}
It is the sample I'm using. I'm fetching the data to display in the aspx output and it works. Now I also need to fetch the same data in this file also.
This is a totally non-standard and inefficient way to do this.
The normal way to do it would be to have a standard aspx page, with some sort of repeater control or datagrid on it that displays the required data, and then you can navigate to that page from elsewhere in your web site. You pass the appropriate variables to the page via the querystring/session/whatever, and the page uses those variables to then select the data it should display.
If you are trying to have a permanent and immutable page created for each visitor to that page, then follow the above advice but look at methods for generating the page as a PDF document instead.
It is strongly recommended that you use the standard ASP.NET way of producing a HTML page (Repeater controls etc...), rather than attempting to write HTML yourself - this is, after all, exactly the task that ASP.NET was designed for!
If you want to see the rendered HTML for an ASP.NET page then you can use code similar to the following:
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(sw);
this.Render(hw);
return sb.ToString();
You need to make sure that you do this late enough in the page lifecycle for the page processing to have completed (for example during SaveStateComplete.)
I would recommend that you go through some ASP.NET tutorials to get a feeling of the framework, and learn how to use it properly. I know it will take some time to get through the tutorials, but I think the time is well spent.
Microsoft's Learn ASP.NET is one place to start. You could probably find a ton more by googling for them.
精彩评论