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">
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;}
}
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" />
}
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
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…