ASP.NET MVC SubString帮助

ASP.NET MVC SubString help

我有一个显示新闻文章的ASP.NET MVC应用程序,对于主要段落,我有一个截断和HTML标记剥离器。例如<pa><%= item.story.RemoveHTMLTags().Truncate() %><pb>

这两个函数来自一个扩展,如下所示:

1
2
3
4
5
6
7
8
9
public static string RemoveHTMLTags(this string text)
{
    return Regex.Replace(text, @"<(.|\
)*?>", string.Empty);
}
public static string Truncate(this string text)
{
    return text.Substring(0, 200) +"...";
}

但是,当我创建一个只有3-4个单词的故事的新文章时,它会抛出此错误:Index and length must refer to a location within the string.
Parameter name: length

出什么问题了?谢谢


将您的截断函数更改为:

1
2
3
4
5
6
7
8
9
10
11
12
public static string Truncate(this string text)
{    
    if(text.Length > 200)
    {
        return text.Substring(0, 200) +"...";
    }
    else
    {
        return text;
    }

}

一个更有用的版本是

1
2
3
4
5
6
7
8
9
10
11
12
public static string Truncate(this string text, int length)
{    
    if(text.Length > length)
    {
        return text.Substring(0, length) +"...";
    }
    else
    {
        return text;
    }

}

问题在于您的length参数比字符串长,因此它会引发异常,正如函数文档所述。

换句话说,如果字符串的长度不超过200个字符,则Substring(0, 200)不起作用。

您需要根据原始字符串的长度动态确定子字符串。尝试:

1
return text.Substring(0, (text.Length > 200) : 200 ? text.Length);