当前位置:编程学习 > asp >>

在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页面中:
view sourceprint?@helper Truncate(string input, int length) 
    if (input.Length <= length) { 
        @input 
    } else { 
        @input.Substring(0, length)<text>...</text> 
    } 
}
然后调用这个方法:
view sourceprint?@Truncate(item.Artist.Name, 25)
 
补充:Web开发 , ASP.Net ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,