Asp.net-Mvc

電話號碼或社會保險號的 DisplayFormat.DataFormatString

  • January 13, 2017

有沒有辦法可以使用DisplayFormat視圖模型屬性上的屬性來應用DataFormatString社會保險號或電話號碼的格式?我知道我可以用 javascript 來做到這一點,但如果可能的話,我更願意讓模型來處理它。

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "???????")]
public string Ssn { get; set; }

以下應該有效,但請注意 Ssn 屬性的類型差異。

[DisplayFormat(DataFormatString = "{0:###-###-####}")]
public long Phone { get; set; }

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:###-##-####}")]
public long Ssn { get; set; }

請注意,為了應用格式,您需要在視圖中使用以下 html 幫助程序:

@Html.DisplayFor(m => m.Property)

如果類型是整數,則接受的答案很好,但是很多 id 最終被鍵入為字元串以防止失去前導零。您可以通過將字元串分成幾部分來格式化字元串,Substring並通過將其粘貼在 DisplayTemplate 中使其可重用。

在裡面/Shared/DisplayTemplates/,添加一個名為Phone.vbhtml

@ModelType String
@If Not IsNothing(Model) AndAlso Model.Length = 10 Then
   @<span>@String.Format("({0}) {1}-{2}",
             Model.Substring(0, 3),
             Model.Substring(3, 3),
             Model.Substring(6, 4))</span>
Else
   @Model
End If

您可以通過以下幾種方式呼叫它:

  1. 只需使用同名數據類型註釋模型上的屬性:
<DataType("Phone")> _
Public Property Phone As String

然後使用簡單的呼叫DisplayFor

@Html.DisplayFor(Function(model) model.Phone)
  1. 或者,您可以按名稱指定要使用的 DisplayTemplate:
@Html.DisplayFor(Function(model) model.VimsOrg.Phone, "Phone")

引用自:https://stackoverflow.com/questions/10981049