Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Currency Formatting MVC

I'm trying to format an Html.EditorFor textbox to have currency formatting, I am trying to base it off of this thread String.Format for currency on a TextBoxFor. However, my text just still shows up as 0.00 with no currency formatting.

<div class="editor-field">
        @Html.EditorFor(model => model.Project.GoalAmount, new { @class = "editor-     field", Value = String.Format("{0:C}", Model.Project.GoalAmount) })

There is the code for what I am doing, and here is the html for that field in the website itself contained within the editor-field div of course.

<input class="text-box single-line valid" data-val="true" 
 data-val-number="The field Goal Amount must be a number." 
 data-val-required="The Goal Amount field is required."
 id="Project_GoalAmount" name="Project.GoalAmount" type="text" value="0.00">

Any help would be appreciated, thanks!

like image 938
Him_Jalpert Avatar asked May 24 '12 16:05

Him_Jalpert


1 Answers

You could decorate your GoalAmount view model property with the [DisplayFormat] attribute:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
public decimal GoalAmount { get; set; }

and in the view simply:

@Html.EditorFor(model => model.Project.GoalAmount)

The second argument of the EditorFor helper doesn't do at all what you think it does. It allows you to pass additional ViewData to the editor template, it's not htmlAttributes.

Another possibility is to write a custom editor template for currency (~/Views/Shared/EditorTemplates/Currency.cshtml):

@Html.TextBox(
    "", 
    string.Format("{0:c}", ViewData.Model),
    new { @class = "text-box single-line" }
)

and then:

@Html.EditorFor(model => model.Project.GoalAmount, "Currency")

or use [UIHint]:

[UIHint("Currency")]
public decimal GoalAmount { get; set; }

and then:

@Html.EditorFor(model => model.Project.GoalAmount)
like image 115
Darin Dimitrov Avatar answered Oct 23 '22 00:10

Darin Dimitrov