asp.net MVC的验证注解对美元汇率 [英] asp.net mvc validation annotation for dollar currency
问题描述
我为 Html.TextBoxFor
验证。这里是我的code ...查看
I am validation for Html.TextBoxFor
. Here is my code on the view
@Html.TextBoxFor(m => m.Amount, new {@class = "form-control", Value = String.Format("{0:C}", Model.Amount) })
这code需要从数据库5000.00一样,并显示在用户界面上的双重价值为$ 5,000.00。然而,当用户点击提交按钮,将显示一个验证错误
This code takes the double value from the database like 5000.00 and displays on the UI as $5,000.00. However when the user hits the submit button, a validation error is displayed that
值'$ 5,000.00'是无效的金额。
The value '$5,000.00' is not valid for Amount.
在模型验证我的注解是
[Range(0, double.MaxValue, ErrorMessage = "Please enter valid dollar amount")]
要得到它提交,我不得不重新输入为5000.00。我该如何解决这个问题?谢谢你。
To get it to submit, I had to retype as 5000.00. How can I fix this? Thanks.
推荐答案
当你做值=的String.Format({0:C},Model.Amount)
在htmlAttributes,剃刀将执行C#code和返回值,$ 125.67
,(假设你的金额
属性是 125.67M
),这是一个字符串。因此,通过您的视图生成的标记为
When you do the value = string.Format("{0:C}", Model.Amount)
in the htmlAttributes, razor will execute the C# code and return the value,"$125.67"
, (Assuming the value of your Amount
property is 125.67M
) which is a string. So the markup generated by your view will be
<input value="$125.67" class="form-control" id="Amount" name="Amount" type="text">
现在因为 $ 125.67
不是不是的Valide十进制值,而是一个字符串。它不能映射该文本框的金额
您的视图模型的财产类型为十进制/ doube的价值。
Now since $125.67
is not not a valide decimal value, but a string. it cannot map the value of this textbox to the Amount
property of your view model which is of type decimal/doube.
您可以做的是,在字符串类型的您的视图模型存储此格式的字符串值,当用户提交表单,尝试解析回小数变量并使用它创建一个新的属性。
What you can do is, create a new property in your view model of type string to store this formatted string value and when user submits the form, try to parse it back to a decimal variable and use it.
因此,一个新的属性添加到您的视图模型
So add a new property to your view model
public class CreateOrderVm
{
public int Id { set;get;}
public string AmountFormatted { set;get;} // New property
public decimal Amount { set;get;}
}
和在你看来,这是强类型为CreateOrderVm
And in your view, which is strongly typed to CreateOrderVm
@model CreateOrderVm
@using(Html.BeginForm())
{
@Html.TextBoxFor(m => m.AmountFormatted, new { @class = "form-control",
Value = String.Format("{0:C}", Model.Amount) })
<input type="submit" />
}
而在你的HttpPost行动
And in your HttpPost action
[HttpPost]
public ActionResult Create(CreateOrderVm model)
{
decimal amountVal;
if (Decimal.TryParse(vm.AmountFormatted, NumberStyles.Currency,
CultureInfo.CurrentCulture, out amountVal))
{
vm.Amount = amountVal;
}
else
{
//add a Model state error and return the model to view,
}
//vm.Amount has the correct decimal value now. Use it to save
// to do :Return something
}
这篇关于asp.net MVC的验证注解对美元汇率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!