Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

asp.net mvc validation annotation for dollar currency

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) })

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

The value '$5,000.00' is not valid for Amount.

My validation annotation on the Model is

[Range(0, double.MaxValue, ErrorMessage = "Please enter valid dollar amount")]

To get it to submit, I had to retype as 5000.00. How can I fix this? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...