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.

About these ads

One Response to “Html helper for showing line breaks from a text area in ASP.NET MVC”

Trackbacks/Pingbacks

  1. ASP.NET MVC Archived Blog Posts, Page 1 - April 12, 2010

    [...] to VoteHtml helper for showing line breaks from a text area in ASP.NET MVC (4/5/2010)Monday, April 05, 2010 from Nick MasaoThis is a quick tip. When getting started with ASP.NET MVC I [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: