Alex Rivera | Logout

asp.net mvc convert \n new line to html breaks

Asked 2011-02-17T17:05:47.370
34

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:

<%= Model.Description%>
Edit
Report

1 Answer

1

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)
answered 2012-02-13T17:20:03.957

Your Answer