文本自动截断

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

能自动截断文本。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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值