Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - MVC3 - 3 decimal places on type double with leading zero

I have a field for weight in Kgs (type double or use something else??). In edit view I would like the user to enter numbers to the thousandth place. In display view I would like the Kgs to appear like 560.250

Trying to learn MVC3 + Razor. Willing to explore JQuery, use of regular expressions, validators, view templates, view models...

The "magic" of MVC based on conventions takes getting used to. Confused as to which approach to use.

Thank you in advance for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use data annotations on your view model:

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

and in your view

@Html.EditorFor(x => x.Weight)

will properly format the value in the input field.

Another possibility is to write a custom editor template for the double type (~/Views/Shared/EditorTemplates/double.cshtml):

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

and then in your view:

@Html.EditorFor(x => x.Weight)

or if you don't want to override all templates for all double types in your application you could put this into some custom template location like ~/Views/Shared/EditorTemplates/MyFormattedDouble.cshtml and then in your view:

@Html.EditorFor(x => x.Weight, "MyFormattedDouble")

Personally I prefer the first approach which uses data annotations to control the format of the double values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...