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
767 views
in Technique[技术] by (71.8m points)

asp.net mvc - DisplayFormat for TextBoxFor in MVC

I need to round off 4 digit decimal to 2 digits and show in MVC 3 UI

Something like this 58.8964 to 58.90

Tried following this How should I use EditorFor() in MVC for a currency/money type? but not working.

As i am using TextBoxFor=> i removed ApplyFormatInEditMode here. Even i tried with ApplyFormatInEditMode , but nothing works. Still showing me 58.8964.

MyModelClass

 [DisplayFormat(DataFormatString = "{0:F2}")]
 public decimal? TotalAmount { get; set; }

 @Html.TextBoxFor(m=>m.TotalAmount)

How can i achieve this round off?

I can't use EditorFor(m=>m.TotalAmount) here, as i need to pass some htmlAttributes

Edit:

After debugging with MVC source code, they internally use

 string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);

in MvcHtmlString InputHelper() method of InputExtension.cs that takes object value as parameter and converting. They are not using any display format there. How could we fix?

I managed to fix in this way. As i have a custom helper, i can able to manage with the below code

 if (!string.IsNullOrEmpty(modelMetaData.DisplayFormatString))
   {
     string formatString = modelMetaData.DisplayFormatString;
     string formattedValue = String.Format(CultureInfo.CurrentCulture, formatString, modelMetaData.Model);
     string name = ExpressionHelper.GetExpressionText(expression);
     string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
       return htmlHelper.TextBox(fullName, formattedValue, htmlAttributes);
   }
   else
   {
       return htmlHelper.TextBoxFor(expression, htmlAttributes);
   }
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This works in MVC5

@Html.TextBoxFor(m => m.TotalAmount, "{0:0.00}")

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

...