属性:
public decimal Cost { get; set; }
html 助手:
<%: Html.TextBoxFor(m => m.Cost)%>
问题:当我设置 Cost
时属性,我该如何格式化它?例如显示两位小数的精度?
最佳答案
我在上面对 Jamiec 的回答进行了一些调整,以 (a) 使其编译并 (b) 使用与框架相同的底层方法:
public static MvcHtmlString DecimalBoxFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, decimal?>> expression, string format, object htmlAttributes = null)
{
var name = ExpressionHelper.GetExpressionText(expression);
decimal? dec = expression.Compile().Invoke(html.ViewData.Model);
// Here you can format value as you wish
var value = dec.HasValue ? (!string.IsNullOrEmpty(format) ? dec.Value.ToString(format) : dec.Value.ToString())
: "";
return html.TextBox(name, value, htmlAttributes);
}
关于c# - 'decimal' 类型和格式的 html 助手?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4617397/