ASP.NET MVC SubString帮助

时间:2011-01-05 23:14:42

标签: asp.net-mvc

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

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

public static string RemoveHTMLTags(this string text)
{
    return Regex.Replace(text, @"<(.|\n)*?>", 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

有什么问题?感谢

2 个答案:

答案 0 :(得分:7)

将截断功能更改为:

public static string Truncate(this string text) 
{     
    if(text.Length > 200)
    {
        return text.Substring(0, 200) + "..."; 
    }
    else
    {
        return text;
    }

} 

更有用的版本是

public static string Truncate(this string text, int length) 
{     
    if(text.Length > length)
    {
        return text.Substring(0, length) + "..."; 
    }
    else
    {
        return text;
    }

} 

答案 1 :(得分:1)

问题是你的长度参数比字符串长,所以它是throwing an exception just as the function documentation states

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

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

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