在我们的项目中经常会因为一个新闻的标题过长而不想全部显示。下面提供一个截断文本的类。
在MVC目录下新建一个名为 Extersions 的文件夹,在该文件夹中新建一个截断文本类,取名为:CutOfTextExtersions
该类代码如下:
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 "";
}
}
}
}
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))