2013-05-27 25 views
3

我怎樣才能在剃刀CSHTML頁面格式的字符串,如果它不再那麼X caracters:替換字符串點結束時,如果字是不再那麼X

<p>@Model.Council</p> 

Example for an X = 9 

-> if Council is "Lisbon", then the result is "<p>Lisbon</p>" 
-> if Council is "Vila Real de Santo António", then the result is "<p>Vila Real...</p>" with the title over the <p> "Vila Real de Santo António" showing the complete information 

感謝。

回答

5

適用於任何字符串。 See here

併爲你的代碼...

@(Model.Council.Length>10 ? Model.Council.Substring(0, 10)+"..." : Model.Council) 
+0

嗨,謝謝你的幫助。由於他的簡單性,我決定爲您的解決方案。再次感謝。 – Patrick

+0

這是我的答案的確切副本 –

+0

它在你之前,或在同一時間。 :( – WhyMe

1
Model.Console.Length <= 9 ? Model.Console : Model.Console.Substring(0, 9) + "..."; 

這是在使用Tirany Operator

它檢查長度小於或等於9,如果是則用左方後? ,如果它是假的,則使用右側,這將在9個字符後截斷字符串並追加"..."

您可以將此權限內聯到您的剃鬚刀代碼中,從而不必調用視圖中的任何代碼。

注意 - 這可能會破壞如果Model.Console爲null或空

+0

嗨,謝謝你的幫助。 – Patrick

5

這裏有一個輔助方法,你可以使用:

public static class StringHelper 
{ 
    //Truncates a string to be no longer than a certain length 
    public static string TruncateWithEllipsis(string s, int length) 
    { 
     //there may be a more appropiate unicode character for this 
     const string Ellipsis = "..."; 

     if (Ellipsis.Length > length) 
      throw new ArgumentOutOfRangeException("length", length, "length must be at least as long as ellipsis."); 

     if (s.Length > length) 
      return s.Substring(0, length - Ellipsis.Length) + Ellipsis; 
     else 
      return s; 
    } 
} 

只需從CSHTML的內部稱之爲:

<p>@StringHelper.TruncateWithEllipsis(Model.Council, 10)</p> 
+0

嗨,謝謝你的幫助 – Patrick

1

就像一個選項一樣,一個Regex.Replace(雖然它可能更容易成爲一個函數並使用常規Substring

Regex.Replace("Vila Real de Santo António", "^(.{9}).+", "$1...") 
+0

嗨,謝謝你的幫助 – Patrick

相關問題