Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

asp.net mvc - Limit to 2 decimals in TextBoxFor

The code below works fine but, in the textbox the decimal value has this format "0,0000" (, is the decimal separator). I'd like have only 2 decimal. How can I do this ?

Thanks,

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

Update 1

In the debugger, I don't see any decimal, wehn I do step by step inside (o @HTML.Textbofor) the view, the value does not have any decimal but when the page is displayed there are 4 decimals

//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"}) 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would use editor templates and I would not use my NHibernate domain models in my views. I would define view models which are specifically tailored to the requirements of the given view (in this case limiting the amount to 2 decimals):

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

and then:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...