我假设我必须搜索回车并将其替换为中断标记?
是的,你的假设是正确的。你可以使用自定义的HTML帮助:
public static IHtmlString FormatBody(this HtmlHelper htmlHelper, string value)
{
if (string.IsNullOrEmpty(value))
{
return MvcHtmlString.Empty;
}
var lines = value.Split('\n'); // Might need to adapt
return htmlHelper.Raw(
string.Join("<br/>", lines.Select(line => htmlHelper.Encode(line)))
);
}
然后:
@Html.FormatBody(Model.Body)
UPDATE:
而这里的单元测试的了这个方法是一个例子:
[TestMethod]
public void FormatBody_should_split_lines_with_br_and_html_encode_them()
{
// arrange
var viewContext = new ViewContext();
var helper = new HtmlHelper(viewContext, MockRepository.GenerateStub<IViewDataContainer>());
var body = "line1\nline2\nline3<>\nline4";
// act
var actual = helper.FormatBody(body);
// assert
var expected = "line1<br/>line2<br/>line3<><br/>line4";
Assert.AreEqual(expected, actual.ToHtmlString());
}
@Darin:谢谢。 – 2011-02-17 10:56:48