asp.net-mvchtml.textboxfor

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..


Solution

  • 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 })