2012-05-24 206 views
29

我試圖格式化一個Html.EditorFor文本框來進行貨幣格式化,我正在試圖從此線程String.Format for currency on a TextBoxFor開始。然而,我的文本仍然顯示爲0.00,沒有貨幣格式。貨幣格式化MVC

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

沒有爲我做什麼的代碼,這裏是本身包含課程的主編場DIV內的網站領域的HTML。

<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"> 

任何幫助將不勝感激,謝謝!

回答

65

您可以與[DisplayFormat]屬性裝飾你的GoalAmount視圖模型屬性:

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

,並在視圖簡單:

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

的EditorFor助手的第二個參數不做所有你認爲它的確如此。它允許您將其他ViewData傳遞給編輯器模板,它不是htmlAttributes。

另一種可能性是寫貨幣的自定義編輯模板(~/Views/Shared/EditorTemplates/Currency.cshtml):

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

然後:

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

或使用[UIHint]

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

,然後:

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

很好,謝謝! :) –

+0

貨幣(磅)沒有便士的格式字符串是什麼?我似乎還沒有找到它。謝謝。 – Doomsknight

+1

@Doomsknight,你有沒有試過''{0:C0}「'? –