I have a textarea
in mvc. When data is entered into that and I\'m displaying it back to the user, how do I show the line breaks?
I display like this:
I think this answer solves the problems in a nice way, just using css: style="white-space: pre-line"
check also: CSS white space property.
You should always encode user entered text when displaying it back in the view to ensure that it is safe.
You could do as Cybernate suggested or could add it to a HtmlHelper extension method
public static string EncodedMultiLineText(this HtmlHelper helper, string text) {
if (String.IsNullOrEmpty(text)) {
return String.Empty;
}
return Regex.Replace(helper.Encode(text), Environment.NewLine, "<br/>")
}
So that it can be easily reused in you view
<%= Html.EncodedMultiLineText(Model.Description) %>
I like using HtmlExtensions, Environment.NewLine and Regex, which were in different answers, so I kinda put the above answers into a single method.
public static MvcHtmlString MultiLineText(this HtmlHelper htmlHelper, string text) {
if (string.IsNullOrEmpty(text)) {
return MvcHtmlString.Create(string.Empty);
}
return MvcHtmlString.Create(Regex.Replace(HttpUtility.HtmlEncode(text), Environment.NewLine, "<br/>"));
}
Use
<%= Html.MultiLineText(Model.MultilineText) %>
Or
@Html.MultiLineText(Model.MultilineText)
The following class implements a HtmlHelper that properly encodes the text:
public static class HtmlExtensions
{
public static MvcHtmlString Nl2Br(this HtmlHelper htmlHelper, string text)
{
if (string.IsNullOrEmpty(text))
return MvcHtmlString.Create(text);
else
{
StringBuilder builder = new StringBuilder();
string[] lines = text.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
if (i > 0)
builder.Append("<br/>\n");
builder.Append(HttpUtility.HtmlEncode(lines[i]));
}
return MvcHtmlString.Create(builder.ToString());
}
}
}
It's easy to use in your views:
<%= Html.Nl2Br(Model.MultilineText) %>
Or with Razor:
@Html.Nl2Br(Model.MultilineText)
The answer above that provides a static HTML helper extension provides an obsolete constructor:
return new MvcHtmlString(builder.ToString());
This line can be replaced by the following line of code:
return MvcHtmlString.Create((builder.ToString()));