0

I'd like the end-user to type in text without any formatting in a text area in my ASP.NET MVC application. However, I would like to retain any line breaks or paragraphs that they have created when typing in their text.

If I use a textarea without allowing HTML input, by default, the line breaks and paragraphs are not retained when this text is saved to the database or read back to be displayed on the user interface.

If I AllowHTML, I run the risk of code injection.

The only other way I can think of implementing this is to not AllowHTML but instead have a custom attribute that checks allows only for <p> tags and <br /> tags, but then for implementing that, simple as it might seem, I will have to maintain a dictionary of all possible HTML tags and, with the nature of the Web being so volatile, god knows what other syntactical tokens from CSS or something.

Am I over-complicating the issue? Is there something out of the box or is there an easier way to implement this?

I am using ASP.NET MVC 5.2.3 targeting ASP.NET 4.5.

5
  • What do you mean retain any line breaks? If the user is just typing plain text and uses the return key to enter a new paragraph, then it will be retained. Commented Jan 29, 2016 at 10:41
  • 1
    But line breaks are retained so not sure why your claiming they are not. If you mean in a display view (e.g. <div>@Model.SomeProperty</div>) you don't see them, its because you need to style the element with whitespace:pre; Commented Jan 29, 2016 at 10:57
  • @StephenMuecke Thank you. That's the right answer. :-) Commented Jan 29, 2016 at 11:21
  • And do it using css, not by replacing the newline characters (which is \n\r, not \n) with a <br/> tag :) Commented Jan 29, 2016 at 11:23
  • I have just answered it here with a more flexible approach: stackoverflow.com/a/44140165/538387 Commented May 23, 2017 at 16:22

1 Answer 1

1

textarea keeps line breaks as \n characters. When displaying the value afterwards outside textarea element as part of the page the '\n' characters need to be replaced with '<br />'.

Sign up to request clarification or add additional context in comments.

1 Comment

For anyone else like me reading this, as @StephenMuecke suggested in the comment to my question, instead of doing the replace operation manually, simply style the element that displays the text with white-space: pre.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.