Feb
3
2009
Extension methods… They’re cool, they’re great, and we all know that they are dangerous…. But….
Current project has a few forms, as always, and I found myself coding and decoding text input data, keeping a secure site, and it dawned on me…
Why don’t we use the features which were so graciously created for us??? Duh!
So here is a down and dirty Extension method to HtmlEncode and HtmlDecode a string…
public static string HtmlEncode(this string value)
{
return HttpContext.Current.Server.HtmlEncode(value);
}
public static string HtmlDecode(this string value)
{
return HttpContext.Current.Server.HtmlDecode(value);
}
If we are populating a form from our application model object, let’s just say a customer, it is easily implemented like so….
FirstNameLabel.Text = customer.FirstName.HtmlDecode();
LastNameLabel.Text = customer.LastName.HtmlDecode();
Or, if we are grabbing data from a form and populating our same application model customer object….
var newCustomer = new Customer
{
FirstName = FirstNameTextBox.Text.HtmlEncode(),
LastName = LastName TextBox.Text.HtmlEncode()
};
Enjoy,
RA