0

I have the following

public decimal? Price {get;set;}

When I enter 3000.00 in to the textbox on the view (textbox below)

  <div class="form-group">
    <label class="col-lg-3 control-label no-padding-right">Price</label>
        <div class="col-lg-5">
            @Html.ValidationMessageFor(m => m.Price)
        <div class="input-group">
            <span class="input-group-addon">£</span>
                @Html.TextBoxFor(m => m.Price, new { @class = "form-control", type = "text", id = "txtPrice", onkeypress = "return isNumberKey(event)" })
        </div>
      </div>
   <label class="col-lg-4 control-label" style="text-align: left">Decimal format</label>

So it would look like this

enter image description here

It saves in the database as 3000.00 which is expected, but when I return back to the view to edit it the value in the textbox is 3000.0000

I have tried some of the solutions on here

Remove trailing zeros of decimal

I think the issue I have is the field on the view is of type decimal not a string, so I'm uncertain on how to format this decimal to remove the trailing zeros so it looks like picture above

Community
  • 1
  • 1
Code Ratchet
  • 5,758
  • 18
  • 77
  • 141
  • 1
    Use the overload that accepts a format string `@Html.TextBoxFor(m => m.Price, "{0:0.00}", new { ....})` –  Feb 08 '15 at 02:36

1 Answers1

0

You need to use the oveload of TextBoxFor that accepts a format string

@Html.TextBoxFor(m => m.Price, "{0:0.00}", new { @class = "form-control", type = "text", id = "txtPrice", onkeypress = "return isNumberKey(event)"})

Side notes:

  1. Remove type="text". The html helper already adds this for you (add is there a reason why you dont just use the default id rendered by the helper, which would be id="Price"?).
  2. Use Unobtrusive Javascript rather that polluting your markup with behavior - e.g. $('#txtPrice').keypress(...
  • Correct I should be using the default Id, I'm just use to writing Id etc so I need to get in to the habit and let helper assign the Id's, I'll also change how the keypress is working to. Thanks again – Code Ratchet Feb 08 '15 at 02:51