TextBoxFor中限制为2位小数

Kri*_*s-I 38 asp.net-mvc asp.net-mvc-3

下面的代码工作正常,但在文本框中,十进制值的格式为"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"}) 
Run Code Online (Sandbox Code Playgroud)

更新1

在调试器中,我没有看到任何小数,我是一步一步在内部(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"}) 
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 62

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

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

然后:

@Html.EditorFor(m => m.Bank.Amount) 
Run Code Online (Sandbox Code Playgroud)

  • @ Kris-I,是的,你需要为每个视图创建一个视图模型.它没有相同的属性.仅限此特定视图使用的属性,并且还包含此特定视图所需的格式设置和验证属性. (2认同)
  • @Kris-I,是的,这个例子对我来说似乎是正确的.确保在您的实际项目中,您在视图中使用`EditorFor`(而不是`TextBoxFor`),并且您作为lambda表达式传递给此EditorFor的属性使用`[DisplayFormat]`属性进行修饰. (2认同)

Ale*_*s B 38

这适合我

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

编辑:

这是TextBoxFor(不适用于MVC3)

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

  • 你正在使用的TextBoxFor的重载是MVC4.如果你还没有注册MVC 4程序集**这将不适用于MVC3** (2认同)

the*_*lem 17

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

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