asp.net-mvc DisplayFormat.DataFormatString 用于电话号码或社会安全号码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10981049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DisplayFormat.DataFormatString for a phone number or social security number
提问by AJ.
Is there a way I can use the DisplayFormatattribute on a view model property to apply a DataFormatStringformat for a social security number or a phone number? I know I could do this with javascript, but would prefer to have the model handle it, if possible.
有没有办法可以使用DisplayFormat视图模型属性上的属性来应用DataFormatString社会安全号码或电话号码的格式?我知道我可以用 javascript 做到这一点,但如果可能的话,我更愿意让模型来处理它。
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "???????")]
public string Ssn { get; set; }
回答by Jesse
The following should work, however notice the type difference for the Ssn property.
以下应该有效,但请注意 Ssn 属性的类型差异。
[DisplayFormat(DataFormatString = "{0:###-###-####}")]
public long Phone { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:###-##-####}")]
public long Ssn { get; set; }
Note, that in order for the formatting to be applied you would need to use the following html helper in your view:
请注意,为了应用格式,您需要在视图中使用以下 html 帮助程序:
@Html.DisplayFor(m => m.Property)
回答by KyleMit
The accepted answer is great if the type is an integer, but a lot of ids wind up being typed as a string to prevent losing leading zeros. You can format a string by breaking it up into pieces with Substringand make it reusable by sticking it in a DisplayTemplate.
如果类型是整数,则接受的答案很好,但是很多 id 最终被输入为字符串以防止丢失前导零。您可以通过将字符串分成几部分来格式化字符串,Substring并通过将其粘贴在 DisplayTemplate 中使其可重用。
Inside /Shared/DisplayTemplates/, add a template named Phone.vbhtml:
在里面/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
You can invoke this in a couple ways:
您可以通过以下几种方式调用它:
Just annotate the property on your model with a data type of the same name:
<DataType("Phone")> _ Public Property Phone As StringAnd then call using a simple
DisplayFor:@Html.DisplayFor(Function(model) model.Phone)Alternatively, you can specify the DisplayTemplate you'd like to use by name:
@Html.DisplayFor(Function(model) model.VimsOrg.Phone, "Phone")
只需使用同名数据类型注释模型上的属性:
<DataType("Phone")> _ Public Property Phone As String然后使用简单的调用
DisplayFor:@Html.DisplayFor(Function(model) model.Phone)或者,您可以按名称指定要使用的 DisplayTemplate:
@Html.DisplayFor(Function(model) model.VimsOrg.Phone, "Phone")

