我正在开发 asp.net mvc 5.2.2。使用 Razor View 引擎的 Web 应用程序。我正在尝试修改默认的 Html.DisplayFor
以在某些 View 上显示 100 个字符的子字符串,后跟“...”?那么这有可能实现吗?
谢谢
最佳答案
Html.DisplayFor
是一个模板化助手。 MVC 为最常见的 C# 类型内置了一些默认模板。不过,对于字符串,它几乎只是按原样转储字符串值。
您可以通过将自己的显示模板添加到 Views\Shared\DisplayTemplates\
来覆盖内置功能。您添加的 View 需要以以下三项之一命名:
- 类型(标准 C# 类型或您自己的类),例如
String.cshtml
、DateTime.cshtml
、Boolean.cshtml
等 DataType
枚举的成员,例如EmailAddress.cshtml
、ImageUrl.cshtml
等(这要求使用适当的DataType
属性来修饰该属性)- 虚拟任何您想要的东西,并使用
UIHint
属性来装饰属性。例如,[UIHint("Foo")]
将使用名为Foo.cshtml
的显示模板。
就您而言,您可以将String.cshtml
与以下内容一起使用:
@model String
@Model.Substring(0, 100)…
但是,我不认为您真的希望将其应用于您网站上任何地方呈现的每个字符串。将 UIHint
与自定义显示模板结合使用可能是更好的选择。创建一个名为 TruncatedString.cshtml
的显示模板,然后使用 [UIHint("TruncatedString")]
装饰您想要显示的任何被截断的属性。
只有当您坚持使用Html.DisplayFor
时才会出现这种情况。实际上,添加一个字符串扩展可能会更好,例如:
public static class StringExtensions
{
public static string Truncate(this string s, int length, string suffix = "...", bool html = false)
{
s = s ?? string.Empty;
s = System.Net.WebUtility.HtmlDecode(s);
if (s.Length > length)
{
s = s.Substring(0, length + 1);
s = s.Substring(0, Math.Min(s.Length, s.LastIndexOf(" ") == -1 ? 0 : s.LastIndexOf(" ")));
s = s + suffix;
}
if (html)
{
return System.Net.WebUtility.HtmlEncode(s.Trim());
}
else
{
return s.Trim();
}
}
}
然后,您可以在您的 View 中执行以下操作:
@Model.SomeLongString.Truncate(100)
关于asp.net-mvc - 我可以修改 Html.DisplayFor 以显示任何字符的子字符串吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28702427/