Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC SubString help

Tags:

asp.net-mvc

I have an ASP.NET MVC app that shows news articles and for the main paragraph I have a truncate and HTML tag stripper. e.g. <p><%= item.story.RemoveHTMLTags().Truncate() %></p>

The two functions are from an extension and are as follows:

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

However when I create a new article say with a story with only 3-4 words it will throw this error: Index and length must refer to a location within the string. Parameter name: length

What is the problem? Thanks

like image 832
Cameron Avatar asked Dec 14 '25 10:12

Cameron


1 Answers

Change your truncate function to this:

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

} 

A much more useful version would be

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

} 
like image 122
Chandu Avatar answered Dec 17 '25 01:12

Chandu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!