Set rendered HTML content to a string for emailing, editing, saving to a database, or more
Ok, so several years ago I had this dilemma. I had to create a receipt for a customer
who made a purchase online. The receipt would emailed to him/her after the purchase was completed.
Sounds simple, right? Well, the problem was the receipt required some heavy HTML to make it
look all spiffy and flashy. The way I did it at the time was by building the HTML on the fly via
code-behind using a StringBuilder. Several months after the implementation, the receipt HTML
was completely changed! Instant maintenance nightmare! So, this time around I did some research.
Man oh man did I feel stupid when I found I could simply take the original HTML given to me and
render it to a string. None of this dynamic HTML BS where I was doing:
sbRecipet.Append("<div style='padding-left:5px;'>Text here!</div>");
Instead this new solution was much more elegant and took me a whole of 10 minutes to implement. Also,
the maintenance was taken out of my hands and placed into those of the peeps who would be updating
the template.
In the sample below I'm taking the content of HTML between a DIV tag in an .ASCX file that contains
a very pretty newsletter. Some labels are filled with user information and the function returns a string
of the rendered HTML output, which we then mail to Newsletter subscribers. The important function is
displayed below. Check it out.
Namespaces required
You'll need the following namespaces for the code:
using System;
using System.IO;
using System.Text;
using System.Web.UI;
Set a rendered HTML Newsletter to a string for emailing
/// <summary>
/// Take the NewsLetter HTML between two DIV tags and push the entire HTML
/// contents to a string value.
/// </summary>
public string GetEmailContent(NewsletterUser oUser)
{
//Populate the template fields
SetFields(oUser);
//Turn view state off while rendering content
this.EnableViewState = false;
//Instantiate objects / Default values
StringBuilder sbBody = new StringBuilder();
StringWriter swWriter = new StringWriter(sbBody);
HtmlTextWriter twEmail = new HtmlTextWriter(swWriter);
//Grab the rendered content of the DataGrids and labels
dvNewsletter.RenderControl(twEmail);
//Return the email content
return sbBody.ToString();
}
I've purposely left out the email method and the user data population method since they really aren't
needed to illustrate the important part of the code. The purpose is to show you how easy it is to
take the rendered HTML of a template and set it to a string value. Now you can email it, parse it,
save it to a database, or do whatever the heck else you want to do with it! Pretty easy, eh?
More information
Drop-In Code