Reputation: 63
I need help to format nullable decimal field as currency (with dollar sign and commas) in mvc application's razor view. Below is my modal and view code.
Model:
[Display(Name = "Eligible Amount")]
[RequiredIfProjectEngineerSelected("ProjectEngineerId", "", ErrorMessage = "Eligible Amount field is Required")]
[DisplayFormat(DataFormatString = "{0:c}")]
public decimal? EligibleAmount { get; set; }
View:
@{var formated = String.Format("{0:c}", decimal)decimal.Parse(@Model.project.ProjectTotalCost.HasValue ? @Model.project.ProjectTotalCost.Value.ToString() : ""));}
@Html.TextBoxFor(model => model.project.ProjectTotalCost, new { @Value = formatted})
It is displaying the formatted currency value in TextBoxFor control. But the problem what I am facing here is, when I am trying to update the value back, getting validation error saying "the value is not matching format".
Upvotes: 2
Views: 4597
Reputation: 63
Thank you for all the suggestions given to me on this. I am able to solve this problem by using the ModelBinder.
As Per Darin's answer, I cannot change the control from TextBoxFor to EditorFor as I need apply styles on that. ModelBinder works with TextBoxFor control also.
~ Balaji
Upvotes: 0
Reputation: 1038840
First things first, you should replace the 2 lines of code you have shown in your view with a single line of code:
@Html.EditorFor(x => x.EligibleAmount)
which will take into account the DisplayFormat
attribute you defined on your model and you don't need to repeat this format in the view. You just need to enable it in edit mode by setting the ApplyFormatInEditMode
property to true
:
[Display(Name = "Eligible Amount")]
[RequiredIfProjectEngineerSelected("ProjectEngineerId", "", ErrorMessage = "Eligible Amount field is Required")]
[DisplayFormat(DataFormatString = "{0:c}", ApplyFormatInEditMode = true)]
public decimal? EligibleAmount { get; set; }
Alright, this solves the displaying part. But the model binding part is still an issue. For that you could write a custom model binder which will take into account the format defined in your DisplayFormat
attribute. I have shown an example of such a model binder with DateTime at this post
. All you have to do is adapt it for the decimal
time which should be a trivial task.
Upvotes: 5