I have a decimal property in my VM:
我的VM中有一个十进制属性:
[Required, Display(Name = "Manual Payment Amount")]
[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
public decimal EnteredPaymentAmount { get; set; }
the View looks like this:
视图看起来像这样:
@Html.TextBoxFor(m => m.EnteredPaymentAmount, new { style = "width:200px", maxlength = Model.MaximumPaymentAmount.ToString("N").Length })
I want to limit the input to only have 2 decimal places
我想限制输入只有2位小数
What is the best way of doing this? I tried to apply the DisplayFormat but also the format on the TextBoxFor but that still passed the validation meaning I can enter say 3 decimal places.
这样做的最佳方式是什么?我试图应用DisplayFormat但也应用TextBoxFor上的格式,但仍然通过验证意味着我可以输入3个小数位。
3 个解决方案
#1
1
You could use some client side plugin that would allow you to define a regular expression for the allowed input. For example the jQuery maskedInput
plugin.
您可以使用一些客户端插件,允许您为允许的输入定义正则表达式。例如jQuery maskedInput插件。
#2
0
$('input#EnteredPaymentAmount').blur(function () {
var num = parseFloat($(this).val());
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
});
I used the above code and it worked just fine.
我使用上面的代码,它工作得很好。
#3
0
How about this:-
这个怎么样:-
@{var formated = String.Format("{0:0.00}", EnteredPaymentAmount);}
@Html.TextBoxFor(m => m.EnteredPaymentAmount, formated, new { id = "id"})
EDIT:-
编辑:-
You can try to use EditorFor
also
您也可以尝试使用EditorFor
@Html.EditorFor(m => m.EnteredPaymentAmount)
#1
1
You could use some client side plugin that would allow you to define a regular expression for the allowed input. For example the jQuery maskedInput
plugin.
您可以使用一些客户端插件,允许您为允许的输入定义正则表达式。例如jQuery maskedInput插件。
#2
0
$('input#EnteredPaymentAmount').blur(function () {
var num = parseFloat($(this).val());
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
});
I used the above code and it worked just fine.
我使用上面的代码,它工作得很好。
#3
0
How about this:-
这个怎么样:-
@{var formated = String.Format("{0:0.00}", EnteredPaymentAmount);}
@Html.TextBoxFor(m => m.EnteredPaymentAmount, formated, new { id = "id"})
EDIT:-
编辑:-
You can try to use EditorFor
also
您也可以尝试使用EditorFor
@Html.EditorFor(m => m.EnteredPaymentAmount)