Reputation: 4503
We are using MVC and I wanted to see if there is another better way to handle this problem. We currently have a decimal field called AmountOfContract declared in a model as:
[DisplayName("Amount Of Contract")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public decimal AmountOfContract { get; set; }
This was displayed on a page using:
@Html.LabelFor(model => model.AmountOfContract, new { @class = "control-label col-md-2" })
<div class="col-md-4">
<div class="input-group m-b">
<span class="input-group-addon">$</span>
@Html.TextBoxFor(model => model.AmountOfContract, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.AmountOfContract)
</div>
</div>
This was working fine. Later our users requested we have the textbox show , (comma) in them, so instead of them typing 10000.00 they show have commas fill in so that would be typed in as 10,000.00
We applied an input mask using autoNumeric.js. that got the mask applied, but if we submitted the form with a value of 10,000.00 the Model.IsValid wold always return false with the model.AmountOfContract being set to 0. This was happening because of the commas being forced into a decimal field, not valid.
The way we got around this was to create another field
[DisplayName("Amount Of Contract")]
public string StrAmountOfContract { get; set; }
This is then used on the form, so the user send and receives a string, that is then getting the Model.IsValid to return true. but then before saving to the db, we need to assign that StrAmountOfContract back to the AmountOfContract.
Is there a better way to do this? As we have a few forms we would have to change in a similar manner.
Upvotes: 0
Views: 3962
Reputation: 598
decimal not accepted value with commas also you can recive value in string and converted it! You can using regular expression to validate price it like:
[DisplayName("Amount Of Contract")]
[RegularExpression(@"^(((\d{1,3})(,\d{3})*)|(\d+))(.\d+)?$",ErrorMessage="The Value format must be 00.00 or 00,00")]
public string AmountOfContract { get; set; }
See Patterns
in your action can convert from string to decimal:
if(ModelState.IsValid)
{
decimal price = Convert.ToDecimal(model.Price.Replace(',','.').ToString());
}
see Model Binding Decimal Values
Upvotes: 1