如何让 Html.DisplayFor 显示换行符? [英] How to make Html.DisplayFor display line breaks?
本文介绍了如何让 Html.DisplayFor 显示换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
令人尴尬的新手问题:
我的模型中有一个包含换行符的 string
字段.
I have a string
field in my model that contains line breaks.
@Html.DisplayFor(x => x.MultiLineText)
不显示换行符.
显然我可以在模型中做一些摆弄并创建另一个字段,将
替换为 <br/>
,但这看起来很笨拙.使这项工作正常进行的教科书方式是什么?
Obviously I could do some fiddling in the model and create another field that replaces
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("
", "<br />
");
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屋!
查看全文