February 2008
Posted on the 2nd at 4:51 PM CST
Creating a "Save As..." Button for the Rendered Markup of an ASP.NET Page
FiledFiled under ASP.NET, Stuff

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.

Comments (3)
Permalink Comment from Sean on February 2nd, 2008 at 11:07 PM
That's it!

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.
Permalink Comment from Len on July 30th, 2008 at 1:59 PM
are you able to give me the code to convert it into an excel file?
Permalink Comment from haziq on December 24th, 2008 at 11:36 PM
saya nak coding button save, edit, delete dan search dari form vb.net ke database

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

Have Your Say

← Answer this to prove you are human
 
 

Chill Out…

No Trackbacks