I have an few editorfor in my view like following
@Html.EditorFor(Model => Model.CashBalance)
Now when i enter any value in to that editorfor,the value should change to currency value in textbox change event
For ex: 123 should display as 123.00 14.35 should display as 14.35
I want to do this in generic way so that I don't need to change it every where as my project has many editorfor which takes inputs from user.
As I am using an EditorTemplate for all these textboxes,i want to handle here itself.
My EditorTemplate for this is decimal.cshtml and it looks like the foll
@model decimal?
@{
string value = (Model.HasValue == false || Model.Value == 0) ? "" : string.Format("{0:0.00}", Model.Value);
}
@Html.TextBox(
"",
value,
new { @class="amountRightAlign"}
)
Will there be any textchange event i can write here so that it affects where ever there is decimal datatype?
Thanks in advance?
Html helpers are server side code used to generate the html which is sent to the client. In order to interact with user changes in the browser, you need to use javascript to handle events.
In your case you don't need an EditorTemplate
. Instead, just the overload of TextBoxFor()
that accepts a format string
@Html.TextBoxFor(m => m.CashBalance, "{0:0.00}", new { @class="decimalnumber" })
Then in the view, or in a separate script file
$('.decimalnumber').change(function () {
var num = new Number($(this).val());
if (isNaN(num)) {
// Its not a valid number
return;
}
$(this).val(num.toFixed(2));
})