TextBoxFor中限制为2位小数

问题描述 投票:35回答:4

下面的代码工作正常,但在文本框中,十进制值的格式为“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

在调试器中,我没有看到任何小数,当我在视图中一步一步(@ HTML.Textboxfor)时,该值没有任何小数但是当显示页面时有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"}) 
asp.net-mvc asp.net-mvc-3
4个回答
58
投票

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

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

然后:

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

37
投票

这适合我

@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"})

15
投票

在MVC 4中,您现在可以将格式作为第二个参数传递

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

1
投票

如果你没有Decimal类型的自定义编辑器模板,那么用EditorFor装饰的DisplayFormatAttribute可能会开箱即用。

对于自定义编辑器模板,我最终使用了以下内容:

@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; }
© www.soinside.com 2019 - 2024. All rights reserved.