Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can limit to 2 decimals in TextBoxFor in MVC?

I want after decimal point only 2 digit.

@Html.TextBoxFor(m => m.Viewers, new { @tabindex = 7 })

Need output like this:

56.23

456.20

1.21

like that..

like image 514
lashja Avatar asked Nov 18 '16 11:11

lashja


1 Answers

I would use editor templates in my views. I would define view models which are specifically tailored to the requirements of the given view (in this case limiting it to 2 decimals):

[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public decimal Viewers{ get; set; }

or You can simply use regular expression with model like

[RegularExpression(@"^\d+.\d{0,2}$")]
public decimal Viewers{ get; set; }

and then in html:

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

or TextBoxFor()will also work with regular expression

@Html.TextBoxFor(m => m.Viewers, new { @tabindex = 7 })
like image 146
MANISH KUMAR CHOUDHARY Avatar answered Oct 13 '22 11:10

MANISH KUMAR CHOUDHARY