MVC3/4 自定义HtmlHelper截断文本内容(截取)
2014-06-05 11:11
344 查看
在MVC目录下新建一个名为 Extersions 的文件夹,在该文件夹中新建一个截断文本类,取名为:CutOfTextExtersions
该类代码如下:
在View中使用该类:
@Html.ActionLink(@Html.GotTopic(@item.NewsTitle, 40, true)) @Html.ActionLink(@Html.GotTopic(@item.NewsTitle, 40, false))
该类代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace System.Web.Mvc //修改为所属System.Web.Mvc命名空间 方便直接使用 { /// <summary> /// 截取字符串类 /// </summary> public static class CutOfTextExtersions { /// <summary> /// 截取字符串方法 /// </summary> /// <param name="helper"></param> /// <param name="str">字符串</param> /// <param name="len">长度</param> /// <param name="flag">是否显示。。。</param> /// <returns></returns> public static string GotTopic(this HtmlHelper helper, string str, int len, bool flag) { if (str != null && str != "") { string clearstr = str.RemoveHTML(); int count = 0; string strTemp = ""; for (int i = 0; i < clearstr.Length; i++) { if (Math.Abs(((int)(clearstr.Substring(i, 1).ToCharArray())[0])) > 255) count += 2; else count += 1; if (count <= len) strTemp += clearstr.Substring(i, 1); else { strTemp = strTemp + (flag == true ? "…" : ""); return str.Replace(clearstr, strTemp); } } return str.Replace(clearstr, strTemp).Replace(" ", "").Trim(); } else return ""; } public static string RemoveHTML(this string str) { try { if (str != "") { str = System.Text.RegularExpressions.Regex.Replace(str, "<[^>]*>", ""); str = str.Replace(" ", " "); return str; } else return ""; } catch { return ""; } } } }
在View中使用该类:
@Html.ActionLink(@Html.GotTopic(@item.NewsTitle, 40, true)) @Html.ActionLink(@Html.GotTopic(@item.NewsTitle, 40, false))
相关文章推荐
- MVC 使用自定义HtmlHelper截断文本内容
- MVC3/4 自定义HtmlHelper截断文本内容
- jsp/java截取截断html内容的方法与技巧
- aspnetpager 获取或设置在显示在用户自定义信息区的用户自定义HTML文本内容。
- C#获取HTML文本的第一张图片与截取内容摘要示例代码
- QLabel嵌入html设置文本内容显示
- 截取带HTML的内容
- Asp.net MVC Preview 4 中自定义Jquery的HtmlHelper扩展
- [译]创建自定义HTML Helper
- 提取文章内容的纯文本,并截取一定的字数
- 创建自定义HTML Helper
- 用java从网络上抓取HTML文件内容并写入本地文本中
- 一个使用Neko提取HTML纯文本内容的程序例子
- JAVA读取WORD,EXCEL,PDF,TXT,RTF,HTML文件文本内容的方法示例
- 创建自定义的HTML Helper
- mvc基础系列说谈(4)——HtmlHelper,自定义,扩展HtmlHelper
- 取HTML中节点中的文本内容
- Asp.net MVC Preview 4 中自定义Jquery的HtmlHelper扩展
- html读出文本文件内容
- Asp.net mvc 创建自定义HTML Helper