I am not sure why you would want to do this, but I have seen the question asked on the ASP.NET forums a couple of times so I figured I would post a solution for it. It is not that difficult to create a "Save As…" button on your web page that, when clicked, will prompt the user with a download dialog containing the rendered markup of the page. All you have to do is have a button that will refresh the page, except append a query string to it. Then in the Page_Load you can check for the existence of the query string and change the content type and disposition of the response to trigger the dialog.
First, add the following markup where you want it on your page…
<input type="button" value="Save Page As…" onclick="(location.href.indexOf('?') == -1) ? location.href += '?save=true' : location.href += '&save=true';" />
All that is doing is adding a query string to the existing URL and redirecting to it. Add this code in the Page_Load to check for the query string and do the necessary steps to force the download prompt…
If Request.QueryString.Item("save") IsNot Nothing Then If Request.QueryString.Item("save").ToString() = "true" Then Response.Clear() Response.ContentEncoding = Encoding.UTF8 Response.ContentType = "text/plain" Response.AddHeader("content-disposition", "attachment") End If End If
And that is all there is to it! This could easily be wrapped up in an ASP.NET User Control so that it could be dropped into several different pages effortlessly. Again, I am not sure why you would want to do this. To me, this is the same as manually viewing the page source and saving it to your hard drive. Oh well, I hope somebody out there finds it useful.
UPDATED 02/03/2008: Shortened onclick event handler for the button.
Another cool thing to do is to change the type to xls (Excel), which allows the user to open it straight up in Excel! I can post some example code later, but it uses the same concept.
Guess What?
There are a few basic guidelines you should be aware of before leaving a comment…
- If you choose to display your email address, it will not be detected by spam bots
- Comments are limited to 3,000 characters; so far you have used none of them
- HTML will be encoded; links and line breaks will be converted automatically
- Comments containing five or more links will be subject to moderation
