views:

26

answers:

2

I have an MVC 2.0 application that takes multiline input from a textarea, then displays the text somewhere else. I would like to have at least paragraphs preserved.

Currently I use the TextArea helper for the form, then Html.Encode the value again when I output it.

// form view
<%: Html.TextAreaFor(model => model.Text, new { cols = 80, rows = 20 })%>

// display view
<div><%: Model.block.Text %></div

Of course this alone is not sufficient. An input of

first line

second line

gets rendered as

<div>first line

second line</div>

which appears as 'first line second line'. Not ideal.

I understand that I could insert the p tags myself into the text, or even have the user input them. However, in this case I would have to disable HtmlEncode for the display page which seems problematic, right? Is there really no better way than to manually strip all tags from the text, then call HtmlEncode, then add p tags, then disable the views automatic encoding?

Incidentially, I have heard people on this forum refer to WYSIWYG editors such as TinyMCE for textarea input. So far I fail to see how this will solve the problem. The editor is not going to do reliable sanitation of the input but would again require me to remove HtmlEncoding on the display page. Once again I'd be faced with writing a complex sanitizer from scratch or simply remove all tags including a and image until the fancy WYSIWYG editor becomes completely meaningless.

Thanks for your time, Duffy

A: 

Could you just replace all new line characters \n with break elements <br /> using something like...

string output = Model.block.Text.Replace ("\n", "<br />");
LeguRi
Ok. But in order to get the desired effect, I'll have to disable Html.Encode on the display page, meaning that it becomes my responsibity to make sure the text doesn't contain vicious code. Am I missing something?
duffy
Hmmmm... I haven't done that much Asp.NET MVC so I'm not certain about that :( sorry
LeguRi
A: 

You could HTML encode the text and then apply the <p> tags

<%= "<p>" + Html.Encode(Model.block.text).Replace("\n", "</p><p>") + "</p>" %>
ZippyV
That will work, although it's a bit too aggressive for my purpose. I don't want to break at every newline, just at every blank newline (multiple newlines). <p>first line\n second line</p>\n \n <p>third line</p>\nI guess that means I need a slightly more complicated matching logic looking for something like `"([\f\r\t\v]*\n){2,}"` which should then probably be residing somewhere in the controller or helper section rather than the view itself. I'll look into extending Html.Encode to accept an optional add_paragraphs value.
duffy