I've been learning
ASP.NET MVC recently, mainly because it's been so long since I worked as a Web developer, I'm completely out-of-touch with what's been going on in the industry over the last eight or so years. I decided it would be nice to learn ASP.NET MVC, as back in the day I was a
PHP developer and had never done any ASP at all.
I'm slowly getting to grips with the whole convention of creating MVC sites and happily working through lots of little problems and issues. One problem I had was how to maintain line-breaks in text, until I figured out a neat little way to do it using a simple extension method on the
HtmlHelper class.
Firstly the extension method itself, which is just a very basic find and replace operation. The only thing to remember is that you need to escape the HTML
before you replace the newlines, otherwise the break-rule tags themselves will be encoded!
using System;
using System.Web.Mvc;
namespace LightBlog.Helpers
{
public static class HtmlHelpers
{
public static string Markup(this HtmlHelper helper, string value)
{
return helper.Encode(value).Replace(Environment.NewLine, "<b r />");
}
}
}
Now that we have our little helper, our next problem is how to make our extension method available in an actual view. To do this we need to add the LightBlog.Helpers namespace to the list of CLR references allowed on each page. We can do this by going into the Web.config file in the main ASP.NET MVC directory and adding a new namespace item to the pages section, like this.
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="LightBlog.Helpers"/>
</namespaces>
</pages>
Now in our view code we can use our custom little Html.Markup method to output our text with the line-breaks intact.
<h1><%= Html.Markup(Model.Text) %></h1>