我正在渲染一個下拉列表,其中下拉列表中顯示的文本太長以至於無法獲得舒適。我該如何限制下拉菜單中顯示的字符數量,而不必返回控制器?視圖是否只呈現字符串的第n個字符
<option value="<%=order.ID %>"><%=order.Item %></option>
THX
我正在渲染一個下拉列表,其中下拉列表中顯示的文本太長以至於無法獲得舒適。我該如何限制下拉菜單中顯示的字符數量,而不必返回控制器?視圖是否只呈現字符串的第n個字符
<option value="<%=order.ID %>"><%=order.Item %></option>
THX
<%= order.Item.Length > 10 ? order.Item.Substring(0, 7) + "..." : order.Item %>
正如丹以下提到,檢查空,拉出到一個輔助方法是一個很好的理念。
public static class StringHelpers
{
public static string SmartSubstring(string value, int maxLength)
{
if(String.IsNullOrEmpty(value))
return String.Empty;
if(value.Length > maxLength)
return value.Substring(0, maxLength -3) + "...";
return value;
}
}
然後只是確保你有這個類在你的aspx的頂部,你可以這樣做:
<%= StringHelpers.SmartSubstring(Order.Item, 10) %>
在order.item使用字符串。如果你想最大是,說出來的話20個字符選擇與串接的前17個字符「...」
我不喜歡在我看來,大量的邏輯,而這種的東西很有用(不僅僅是在視圖中)。
<option value="<%=order.ID %>"><%=order.Item.Truncate(10) %></option>
而截斷方法...
public static class StringExtensions
{
public static string Truncate(this string value, int trim)
{
//Don't do anything if the value is null, empty, or doesn't meet our trim constraint
if (string.IsNullOrEmpty(value) || value.Length <= trim)
{
return value;
}
return string.Format("{0}...", value.Substring(0, trim));
}
}
警告: 我沒有修剪省略號斷的長度。如果你想,你應該做一些額外的檢查以確保(trim-3)大於零。另外,你應該考慮是否修剪長度大於字符串的長度。我會的,但我的大腦正在關閉過夜!
我不喜歡這樣,因爲空字符串將在這裏引起對象引用異常。在檢查字符串的長度之前,最好檢查字符串是否爲空或空。此外,這種觀點中的一大塊邏輯可能會轉移到幫手中,並且會促進可重用性,因爲這類事情在很多地方都很有用。 – 2009-10-10 18:51:27
@Matt!好答案!如果將其更改爲「此字符串值」,那麼它將作爲擴展名工作,因此您可以只執行「Order.Item.SmartSubstring(10)」。 – 2009-10-10 19:07:48
當構建viewmodel發送到頁面時,這種東西也可以在控制器中完成。這樣,你可以圍繞它進行一些測試,並將代碼保留在視圖之外。 – 2009-10-10 19:09:04