,剃刀将执行C#代码并返回值"$125.67"
(假设Amount
属性的值为125.67M
),它是一个字符串。因此,通过您的视图生成的标记将
<input value="$125.67" class="form-control" id="Amount" name="Amount" type="text">
现在既然$125.67
不是不是的Valide十进制值,而是一个字符串。它不能将此文本框的值映射到您的视图模型的Amount
属性,该属性为十进制/双重类型。
你可以做的是,在你的视图模型中创建一个新的属性来存储这个格式化的字符串值,当用户提交表单时,尝试将它解析回一个十进制变量并使用它。
因此,一个新的属性添加到您的视图模型
public class CreateOrderVm
{
public int Id { set;get;}
public string AmountFormatted { set;get;} // New property
public decimal Amount { set;get;}
}
而且在你看来,这是强类型到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行动
[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
}
取看看这个http://stackoverflow.com/questions/34550361/how-do-i-properly-format-a-readonly-textboxfor-value-as-currency – Shyju