2011-01-05 8 views
3

뉴스 기사를 표시하는 ASP.NET MVC 앱이 있고 기본 단락에 잘라내 기와 HTML 태그 스트리퍼가 있습니다. 예 :ASP.NET MVC SubString 도움말

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

을 다음과 같이

두 기능 <p><%= item.story.RemoveHTMLTags().Truncate() %></p>은 확장에서하고 있습니다

무엇이 문제입니까? 감사합니다

+1

내가 가진 유일한 사람이 될 수없는 것 이 주제가 유용하다는 것을 알게되었습니다. – Myzifer

답변

7
이로 잘라 내기 기능을 변경

:

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

} 

훨씬 더 유용 버전은 164 개보기 중

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

} 
+0

완벽하게 작동합니다. 고맙습니다 :) – Cameron

1

문제는 길이 매개 변수가 문자열보다 길기 때문에 throwing an exception just as the function documentation states입니다.

즉, 문자열 길이가 200 자이 아닌 경우 Substring(0, 200)이 작동하지 않습니다.

원본 문자열의 길이에 따라 부분 문자열을 동적으로 결정해야합니다. 시도 :

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

Okies 어떻게 해결할 수 있습니까? 기본적으로 원하는 것은 200 자 이상의 이야기를 자르는 것입니다. 값이 200보다 작 으면 자르지 않아야합니다. – Cameron

+0

완벽하게 작동합니다. 고마워요 :) – Cameron