,剃刀將執行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