ASP.NET MVC中页面中进行自定义文字截取

效果如下:

其实截取方法跟aspx页面中一样,不管是用C#还是js或者CSS都可以实现,

我在这里只是想记录在MVC中怎么用的两种方法:

方法一:

先新建一个类

然后编写以下方法:

public static class HtmlHelpers
{
public static string Truncate(this HtmlHelper helper, string input, int length)
{
if (input.Length <= length)
{
return input;
}
else
{
return input.Substring(0, length) + "...";
}
}
}

在web.config中此处进行注册

添加以下信息:

<add namespace="(your solutionname).Helpers"/>

最后就是在View页面中用了:

<%: Html.Truncate(item.Title, 25) %> (MVC2写法)

@Html.Truncate(item.Artist.Name, 25) (MVC3写法)

方法二(MVC3):

直接在View页面中:

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

然后调用这个方法:

@Truncate(item.Artist.Name, 25)
posted @ 2011-05-25 11:44  peter cheng  阅读(1927)  评论(7编辑  收藏  举报