我需要将4位十进制数舍入2位数字,并显示在MVC 3 UI中。
类似于58.8964到58.90
尝试跟踪这个How should I use EditorFor() in MVC for a currency/money type?,但不起作用。
在使用TextBoxFor=>时,我在这里删除了ApplyFormatInEditMode。就连我也试过用ApplyFormatInEditMode,但都没有用。还在给我看58.8964。
MyModelClass
[DisplayFormat(DataFormatString = "{0:F2}")]
public decimal? TotalAmount { get; set; }
@Html.TextBoxFor(m=>m.TotalAmount)我怎样才能完成这一轮?
我不能在这里使用EditorFor(m=>m.TotalAmount),因为我需要传递一些htmlAttributes
编辑:
在使用MVC源代码进行调试之后,它们内部使用
string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);在MvcHtmlString中,InputExtension.cs的InputHelper()方法以对象值作为参数并进行转换。他们没有使用任何显示格式。我们怎么解决呢?
我设法用这种方法修好了。由于我有一个自定义助手,所以我可以使用下面的代码来管理
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);
}发布于 2013-02-05 07:48:07
如果您希望考虑到自定义格式,则应该使用Html.EditorFor而不是Html.TextBoxFor:
@Html.EditorFor(m => m.TotalAmount)还请确保已将ApplyFormatInEditMode设置为true:
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal? TotalAmount { get; set; }DisplayFormat属性只用于模板化的帮助程序,如EditorFor和DisplayFor。这是推荐的方法,而不是使用TextBoxFor。
发布于 2014-07-10 06:20:54
这在MVC5中是可行的
@Html.TextBoxFor(m => m.TotalAmount, "{0:0.00}")发布于 2013-02-05 06:24:57
就像这样:
@{
var format = String.Format("{0:0.00}", Model.TotalAmount);
}
@Html.TextBoxFor(m => m.TotalAmount, format)希望能帮上忙。
https://stackoverflow.com/questions/14700873
复制相似问题