如何使用MVC Html Helpers截断字符串?

Ref*_*din 7 .net c# asp.net-mvc

我试图截断一个长字符串只在我的索引页面上显示.它显示如下:

<td>
    @Html.DisplayFor(modelItem => item.Description)
</td>
Run Code Online (Sandbox Code Playgroud)

描述可以是500个字符长,但我不能在该网格布局上显示那么多.我只想显示前25个,因为他们可以在详细信息页面上看到所有这些,但我似乎无法让它在模型级别截断它.

像这样的东西会很好:

@Html.DisplayFor(modelItem => item.Description.Take(25))
@Html.DisplayFor(modelItem => item.Description.Substring(0,25)
Run Code Online (Sandbox Code Playgroud)

编辑

当我尝试任一方法时,我在运行时遇到以下异常.

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Run Code Online (Sandbox Code Playgroud)

Nat*_*n A 22

不要使用html帮助器.这样做:

@item.Description.Substring(0, Math.Min(item.Description.Length, 25));
Run Code Online (Sandbox Code Playgroud)

我假设你在某个循环中item当前元素.

  • 如果字符串不超过25个字符,那将抛出一个`ArgumentOutOfRangeException`. (2认同)

48k*_*ocs 5

您可以使用扩展方法执行此操作.

public static string Truncate(this string source, int length)
{
    if (source.Length > length)
    {
        source = source.Substring(0, length);
    }

    return source;
}
Run Code Online (Sandbox Code Playgroud)

然后在你看来:

@item.Description.Truncate(25)
Run Code Online (Sandbox Code Playgroud)