Tag Archives: helpers

Html helper for showing line breaks from a text area in ASP.NET MVC

5 Apr

This is a quick tip. When getting started with ASP.NET MVC I used to have problems for example when I got some user input inside a textarea and wanted to show this text with the html <br /> tags instead of the system newlines.  I couldn’t get it to work. The line breaks never used to display and the text displayed as one really long paragraph.

So I created this simple custom html helper that takes input from your source and properly formats it to show the line breaks. For lack of a better name,  I called it FormatLines. Here’s the code.


namespace WebUI.Helpers
{
    public static class FormatLinesHelper
    {
        public static string FormatLines(this HtmlHelper helper, string stringToFormat)
        {
            StringBuilder sb = new System.Text.StringBuilder();
            StringReader sr = new System.IO.StringReader(stringToFormat);
            string buffer = null;
            do
            {
                buffer = sr.ReadLine();
                if (buffer != null)
                {
                    sb.Append(buffer);
                    sb.Append("<br />");
                }
            } while (buffer != null);

            return sb.ToString();
        }
    }
}

Usage.

Before you use it make sure to compile the code and import the namespace containing this helper method. You can do the import right in your target view like so …

<%@ Import Namespace=”WebUI.Helpers” %>

or include it in the web.config file under the namespaces section like so …

<add namespace=”WebUI.Helpers”/>

Use the helper anywhere in your view like so …

<%= Html.FormatLines (Html.Encode(Model.Notes)) %>

And your text will clearly be displayed with the new lines.

If you look at the source of the page, you’ll see the <br /> tags placed where your new lines used to be.

Hope this was helpful,

Till next time, yours truly.

Follow

Get every new post delivered to your Inbox.