2014-09-02 30 views

回答

9

你可以這樣做:

@Html.LabelFor(m => m.Description, 
       string.Format("{0}:", Html.DisplayNameFor(m => m.Description))) 

DisplayNameFor爲您提供沒有標籤標記的屬性的顯示名稱,因此您可以將其用作中labelText參數的一部分,並根據需要對其進行格式化。這樣您仍然可以獲得動態生成的標籤文本的好處。

在其自己的助手輕鬆地包裹起來:

public static MvcHtmlString LabelWithColonFor<TModel, TValue>(
       this HtmlHelper<TModel> helper, 
       Expression<Func<TModel, TValue>> expression) 
{ 
    return helper.LabelFor(expression, string.Format("{0}:", 
               helper.DisplayNameFor(expression))); 
} 

然後:

@Html.LabelWithColonFor(m => m.Description) 
+0

我有一個HTML格式的MvcHtmlString作爲輸入的LabelText的參數helper.LabelFor當調用時只是helper.DisplayNameFor(exptression)。 這會導致輸出顯示特殊字符,例如「ø」爲「&oslash;」在標籤文本中。我發現最簡單的解決方案是使用HttpUtility.HtmlDecode再次解碼編碼的html,如下所示: 'return helper.LabelFor(expression,string.Format(「{0}:」,System.Web.HttpUtility.HtmlDecode helper.DisplayNameFor(expression).ToString())));' 我歡迎任何簡單的解決方案。 – 2016-01-05 15:39:48

+0

這很有幫助。謝謝! – 2017-05-17 14:51:18

0

下面是一個重複的問題和答案的鏈接。

Postfix label text with colon

這是很好的,因爲結腸是一個真正的設計元素,而不是視圖模型的顯示名屬性的一部分。這很好,因爲冒號會顯示在任何使用diaplayname屬性的驗證消息中。

而且CSS非常簡單。

0

在.NET 4.6+,您可以利用的interpolated strings

<label>@($"{Html.DisplayNameFor(m => m.Description)}:")</label> 

或者,如果你喜歡詳細的版本

@Html.LabelFor(m => m.Description, $"{Html.DisplayNameFor(m => m.Description)}:") 
+2

您的「詳細」選項在功能上有所不同 - 「LabelFor」將標籤與字段ID相關聯,從而允許用戶通過單擊標籤來選擇字段。 – 2016-01-05 16:58:47

相關問題