While I was working on a web shopping project, we were creating email templates to send to users regarding order status. Sometimes we need to format the email template by using some HTML tags like <div> or <br>, which was prevented by ASP.Net. Every time you try to submit HTML tags within the ASP.Net textbox, you get the System.Web.HttpRequestValidationException. So I decided to find a way to encode the tags using javascript first to allow data to be processed by server then at the server action I decoded it to have the original HTML tags inserted into database. Here is the script I added to my aspx page.
<script type="text/javascript">
function escapeHTML (str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
function HTMLEncode()
{
document.getElementById('<%= txtBox.ClientID %>').value = escapeHTML(document.getElementById('<%= txtBox.ClientID %>').value);
}
</script>
This is the button that is used for submitting data to server and hence inserting into database.
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClientClick="HTMLEncode()" OnClick="btnAdd_Click" />
And finally the server side decode which transfers the HTML tags back to their original status.
protected void btnAdd_Click(object sender, EventArgs e)
{
string Value = HttpUtility.HtmlDecode(txtBox.Text);
//Insert Value into database
}
I hope you find this useful.
<script type="text/javascript">
function escapeHTML (str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
function HTMLEncode()
{
document.getElementById('<%= txtBox.ClientID %>').value = escapeHTML(document.getElementById('<%= txtBox.ClientID %>').value);
}
</script>
This is the button that is used for submitting data to server and hence inserting into database.
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClientClick="HTMLEncode()" OnClick="btnAdd_Click" />
And finally the server side decode which transfers the HTML tags back to their original status.
protected void btnAdd_Click(object sender, EventArgs e)
{
string Value = HttpUtility.HtmlDecode(txtBox.Text);
//Insert Value into database
}
I hope you find this useful.