Tuesday 24 January 2017

Replace line break characters with in ASP.NET MVC Razor view

Applying the DRY principle to Omar's solution, here's an HTML Helper extension:


using System.Web.Mvc;
using System.Text.RegularExpressions;
namespace System.Web.Mvc.Html {
public static class MyHtmlHelpers {
public static MvcHtmlString EncodedReplace(this HtmlHelper helper, string input, string pattern, string replacement) {
return new MvcHtmlString(Regex.Replace(helper.Encode(input), pattern, replacement));
}
}
}

Usage (with improved regex):


@Html.EncodedReplace(Model.CommentText, "[\n\r]+", "
")

This also has the added benefit of putting less onus on the Razor View developer to ensure security from XSS vulnerabilities.




My concern with Jacob's solution is that rendering the line breaks with CSS breaks the HTML semantics.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...