如何使Html.DisplayFor显示换行符? [英] How to make Html.DisplayFor display line breaks?
本文介绍了如何使Html.DisplayFor显示换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尴尬的新手问题:
我有一个字符串
字段在我的模型包含换行符。
I have a string
field in my model that contains line breaks.
@Html.DisplayFor(x => x.MultiLineText)
不显示换行符。
很显然,我可以做一些摆弄模型,并创建另一个领域,它取代 \\ n
与< BR />
,但似乎缺憾。什么是教科书的方式,使这项工作?
Obviously I could do some fiddling in the model and create another field that replaces \n
with <br/>
, but that seems kludgy. What's the textbook way to make this work?
推荐答案
一个的HtmlHelper扩展方法换行显示字符串值:
A HtmlHelper extension method to display string values with line breaks:
public static MvcHtmlString DisplayWithBreaksFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var model = html.Encode(metadata.Model).Replace("\r\n", "<br />\r\n");
if (String.IsNullOrEmpty(model))
return MvcHtmlString.Empty;
return MvcHtmlString.Create(model);
}
然后就可以使用下面的语法:
And then you can use the following syntax:
@Html.DisplayWithBreaksFor(m => m.MultiLineField)
这篇关于如何使Html.DisplayFor显示换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文