开发者

Format strongly-typed element value

I have property of type double in my ViewModel and I have create a TextBox for it:

Html.TextBoxFor开发者_运维百科(m => m.DoubleProperty)

Is there any way to format text box value (for example, to apply some String.Format magic)?


You could decorate your view model property with the [DisplayFormat] attribute allowing you to specify any format:

[DisplayFormat(DataFormatString = "{0:###.###}", ApplyFormatInEditMode = true)]
public double? DoubleProperty { get; set; }

and in your view use the EditorFor helper:

@Html.EditorFor(m => m.DoubleProperty)

Another possibility is to write a custom editor template (~/Views/Shared/EditorTemplates/MyDouble.cshtml):

@model double?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("###.###") : "")

and in your view:

@Html.EditorFor(m => m.DoubleProperty, "MyDouble")

or if you don't want to explicitly specify the MyDouble custom editor template when calling the EditorFor helper you could also use the [UIHint] attribute on your view model:

[UIHint("MyDouble")]
public double? DoubleProperty { get; set; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜