2011-02-02 58 views
1

我必須將我的小數顯示爲00.00。我有以下EditorTemplate使用編輯器模板進行變化顯示

@model Decimal? 

@if (Model.HasValue) 
{ 
    @Model.Value.ToString("00.00"); 
} 

我必須在文本框和標籤以及顯示小數。我如何使用上述模板以所需格式顯示以下內容。

@Html.TextBoxFor(m=>@item.Price) 
@Html.LabelFor(m=>@item.Price) 

回答

3

你可以使用你的模型的[DisplayFormat]屬性:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:00.00}", NullDisplayText = "")] 
public decimal? Price { get; set; } 

,然後顯示:

@Html.DisplayFor(x => x.Price) 

,並編輯:

@Html.EditorFor(x => x.Price) 
0

在模板中可以使用

@Html.TextBox("", (Model.HasValue ? Model.Value.ToString("00.00") : String.Empty)) 

@if (Model.HasValue) { 
    @Model.Value.ToString("00.00"); 
    @Html.TextBox("", Model.Value.ToString("00.00")) 
} 
在視圖中使用

然後

@Html.EditorFor(m => m.Price)%> 
+0

所提供的代碼i`ve,我可以做得很好了文本框。位如何做到這一點與labelFor和TexboxFor? – learning 2011-02-02 10:15:30

+0

使用@Html.EditorFor()在您的視圖中顯示模板 – 2011-02-02 11:11:04

0

下創建一個視圖 Decimal.ascx \共享\ EditorTemplates文件夾

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<decimal?>" %> 
<% 
Html.LabelFor(m => m); 
Html.TextBox (ViewData.TemplateInfo.GetFullHtmlFieldId(string.Empty), 

Model.HasValue? Model.Value.ToString( 「00.00」): 「00.00」, 新{只讀= 「只讀」}) %>

如果你需要被顯示出來,在顯示這種情況下開關編輯器(DisplayTemplates ,DisplayFor等) 只讀屬性是使文本框只讀(不可編輯)