在TextBoxFor中限制为2个小数

下面的代码工作正常,但在文本框中的十进制值具有这种格式“0,0000”(,是小数点分隔符)。 我只想要2位小数。 我怎样才能做到这一点 ?

谢谢,

//Database model used with NHibernate public class Bank { public virtual int Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName{ get; set; } public virtual decimal Amount { get; set; } } //MVC Model public class MyModel { public Bank Bank { get; set; } } //View @Html.TextBoxFor(m => m.Bank.Amount, new { id = "tbAmount"}) 

更新1

在debugging器中,我没有看到任何小数,我在内部(o @ HTML.Textbofor)一步一步地查看视图,该值没有任何小数,但是当页面显示时有4位小数

 //Database model used with NHibernate public class Bank { public virtual int Id { get; set; } public virtual string FirstName { get; set; } public virtual string LastName{ get; set; } public virtual decimal Amount { get; set; } } //Class for view public class ViewBank { [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)] public decimal Amount { get; set; } } //MVC Model public class MyModel { public Bank Bank { get; set; } var ViewBank = new ViewBank() { Amount = Bank.Amount}; } //View @Html.TextBoxFor(m => m.Amount, new { id = "tbAmount"}) 

更新2

我做了一个小例子: http : //goo.gl/RKtwY

我会使用编辑器模板,我不会在我的意见中使用我的NHibernate域模型。 我将定义视图模型,这是专门针对给定的视图的要求(在这种情况下限制为2个小数):

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

接着:

 @Html.EditorFor(m => m.Bank.Amount) 

这对我有用

 @Html.TextBox("Amount", String.Format("{0:0.00}", Model.Bank.Amount), new { id = "tbAmount"}) 

编辑:

这是TextBoxFor(不适用于MVC3)

 @{var formated = String.Format("{0:0.00}", Model.Bank.Amount);} @Html.TextBoxFor(m => m.Bank.Amount, formated, new { id = "tbAmount"}) 

在MVC 4中,您现在可以将格式作为第二个parameter passing

 //View @Html.TextBoxFor(m => m.Bank.Amount, "{0:n2}", new { id = "tbAmount"}) 

如果您没有Decimaltypes的自定义编辑器模板,则使用DisplayFormatAttribute EditorFor将可能开箱即用。

对于一个自定义的编辑器模板,我最终使用类似于:

 @model decimal? @{ string displayValue; if (Model == null) { displayValue = null; } else { var formatString = (ViewData.ModelMetadata).DisplayFormatString; displayValue = formatString == null ? Model.ToString() : string.Format(formatString, Model); } } <div class="form-group"> @Html.LabelFor(c => c) @Html.TextBoxFor(c => c, new { type = "text", Value = displayValue, @class = "form-control" }) @Html.ValidationMessageFor(c => c) </div> 

当这个属性用DisplayFormatAttribute装饰时,这是有效的:

 [DisplayFormat(DataFormatString = "{0:n1}", ApplyFormatInEditMode = true), Display(Name = "Commission")] public decimal? CommissionPercentage { get; set; } 

如果您正在使用entity framework,只需在模型浏览器的entity framework中的所需属性上设置Scale即可。