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

查看:22
本文介绍了'十进制'类型和格式的html助手?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

属性:

公共十进制成本{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")%>

这篇关于'十进制'类型和格式的html助手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆