Saturday 31 July 2010

Razor view engine and line breaks

I've been messing around with ASP.NET MVC 3 (preview 1) and one of the problems I needed to get round was how to keep line breaks in user entered text using the new Razor view engine. It turned out to be rather simple, as usual, although the solution was not immediately obvious.

Basically, Razor will automatically encode all strings as HTML, which is a great boon to security, but obviously there are situations where you want to maintain your own encoding. Well, turns out that Razor will leave the string alone if it's already a type of MvcHtmlString, which means that we can update our previous little extension method example to return an MVC string instead of a .NET one.
using System;
using System.Web.Mvc;

namespace LightBlog.Helpers
{
    public static class HtmlHelpers
    {
        public static MvcHtmlString Markup(this HtmlHelper helper, string value)
        {
            value = helper.Encode(value).Replace(Environment.NewLine, "<br / >");
            return new MvcHtmlString(value);
        }
    }
}
By returning an MVC string, Razor will leave our encoding alone, meaning we can now define which HTML tags we want to be displayed. Having done that, we just need to find a way to use our extension method from within a Razor view. This is simple however.
@inherits System.Web.Mvc.WebViewPage<LightBlog.Model.Post>
@using LightBlog.Helpers

@{
    View.Title = "View Post";
    LayoutPage = "~/Views/Shared/_Layout.cshtml";
}

<p>@Html.Markup(Model.Text)</p>
As you see all we need to do is to include a using reference to our Helpers namespace at the top of the view, then we can use our little Markup extension exactly as before!

No comments:

Post a Comment