文本自动截断

比如一个项目中,显示全部书籍列表的页面有一个潜在的问题,如果书名或者作者名过长,将会破坏整个页面的表格完整,所以我们可以创建自定义函数;以便在文本过长的时候

能自动截断文本。Razor的@语法可以很轻易地创建自己的helper函数以用于您的视图。

@helper Truncate(string input,int length)
{
    if(input.Length<=length)
   {
       @input
   }
   else
    {
         @input.Substring(0,length)<text>...</text>
    }
}

要显示的页面里中应该填写该函数以及参数

<td>
   @Truncate(item.Authors,10)
</td>

整个页面的完整代码可以实现文本自动截断的是:

@model IEnumerable<MvcBookStore.Models.Books>

@{
    ViewBag.Title = "书籍管理";
}
@helper Truncate(string input,int length)
{
        if (input.Length <= length)
        {
            @input 
        }
        else
        {
            @input.Substring(0,length)<text>...</text> 
        }
}

<h2>书籍列表</h2>

<p>
    @Html.ActionLink("  新建书籍", "Create")
</p>
<table class="table">
    <tr>
        <th>
            书名
        </th>
        <th>
           价格
        </th>
        <th>
            作者
        </th>
        <th>
           类别
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Truncate(item.Title,25)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Truncate(item.Authors,10)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Categories.Name)
        </td>
        <td>
            @Html.ActionLink("编辑", "Edit", new { id=item.BookId }) |
            @Html.ActionLink("书籍明细", "Details", new { id=item.BookId }) |
            @Html.ActionLink("删除", "Delete", new { id=item.BookId })
        </td>
    </tr>
}

</table>
原文地址:https://www.cnblogs.com/772933011qq/p/4518647.html