Altaf Khatri
How To Insert HTML Tags in TextArea?
When there is a need to accept HTML on the webpage, the control one thinks to accept this HTML from the end user is textarea. This control is very powerful as it can accept new line carriage and lots of information just as any text editor takes.
When accepting HTML through the textarea, once faces lots of challenges. One of the challenge is How to insert html tags in textarea?
There are 2 steps:
-
First, stop the event validation of the page. This is dangerous and should be only done when the end user is safe. Stoping event validation exposes your website to HTML injections.
How to stop event validation? The discussion at hand is related to ASP.NET page.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" ValidateRequest="false" EnableEventValidation="false"%>
EnableEventValidation = false resets the event validation of the ASP.NET page. No more validations for HTML injection while submitting the page. -
Start inserting HTML tags - Disabling event validation, will safely accept the following characters: < equals less thanThe problem arises when there is a need to render the exact HTML tag on the page. What I mean by rendering the exact HTML tags? Suppose I want to insert the following text with formatting:
> equals greater than
& equals ampersand.
<p>This is testing for less than < sign which is < testing success. Solution success </p>
When this page is posted, it is saved as exact text as you see here. But the problem is when this text is retrieved from the database and inserted into the textarea. What does textarea show now:
<p>This is . .testing for less than < sign which is < . . . .testing success. Solution success </p>
See the spacing and the less than sign rendered which is not supposed to.Let's discuss the solution.
While saving the data from the textarea to the database nothing needs to be done. What you have inserted in the html textarea is what is saved in the database. Now after retrieving the data from the database and assigning to the textarea, in the codebehind do the following:articleContent = articleContent.Replace("&", "&");
articleContent = articleContent.Replace("<", "<");
articleContent = articleContent.Replace(">", ">");
Now assigning articleContent variable to the textarea. Please see this code needs to be executed in the codebehind.
For the inquisitives: Second point above - why it happens: This only happens when: i. Using the textarea alone and not with the runat="server" attribute or
ii. server side textarea control:
