MVC 使用自定义HtmlHelper截断文本内容

方法一:

1.在cshtml页面定义方法

@helper Truncate(string input,int length)

{

if(input.Length<=length)

{

@input

}

else

{

@input.Substring(0,length)<text>...</text>

}

}

2.调用

@Truncate(item.Title,20)


方法二:

1.定义方法

using System.Web.Mvc;


namespace MvcMusicStore.Helpers

{

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) + "...";

}

}

}

}

2.在视图的web.config中添加

<add namespace="MvcMusicStore.Helpers" />

3.在cshtml页面调用

@Html.Truncate(item.Title,20)

注:如果在页面中调用不到方法,则重启解决方案,就可解决