'十进制'类型和格式的html助手? [英] html helpers for 'decimal' type and formatting?

查看:8

问题描述

属性:

公共十进制成本{get;放;}

html 助手:

<%: Html.TextBoxFor(m => m.Cost)%>

问题:当我设置 Cost 属性时,如何格式化?例如显示两位小数的精度?

Question: when I am setting the Cost property, how do I format it? for example show a precision of two decimal points?

推荐答案

你可以定义自己的扩展方法,比如:

You could define your own extension method, something like:

public static MvcHtmlString DecimalBoxFor<TEntity>(
            this HtmlHelper helper,
            TEntity model,
            Expression<Func<TEntity, Decimal?>> property,
            string formatString)
        {
            decimal? dec = property.Compile().Invoke(model);

            // Here you can format value as you wish
            var value = !string.IsNullOrEmpty(formatString) ? 
                              dec.Value.ToString(formatString) 
                            : dec.Value.ToString();
            var name = ExpressionParseHelper.GetPropertyPath(property);

            return helper.TextBox(name, value);
        }

然后用法是:

<%Html.DecimalBoxFor(Model,m => m.Cost,"0.00")%>
查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆