"十进制"类型和格式的html助手?

Voo*_*ild 6 c# format asp.net-mvc

属性:

public decimal Cost { get; set; }

html助手:

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

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

Gaz*_*Gaz 14

我稍微调整了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);
}
Run Code Online (Sandbox Code Playgroud)


小智 11

我推荐DisplayFor/EditorFor模板助手.

// model class
public class CostModel {
  [DisplayFormat(DataFormatString = "{0:0.00}")]
  public decimal Cost {get;set;}
}

// action method
public ActionResult Cost(){
  return View(new CostModel{ Cost=12.3456})
}

// Cost view cshtml
@model CostModel

<div>@Html.DisplayFor(m=>m.Cost)</div>
<div>@Html.EditorFor(m=>m.Cost)</div>

// rendering html
<div>12.34</div>
<div><input class="text-box single-line" id="Cost" name="Cost" type="text" value="12.34" /></div>
Run Code Online (Sandbox Code Playgroud)

希望这有帮助.


Jam*_*iec 10

您可以定义自己的扩展方法,例如:

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);
        }
Run Code Online (Sandbox Code Playgroud)

然后用法是:

<%Html.DecimalBoxFor(Model,m => m.Cost,"0.00")%>
Run Code Online (Sandbox Code Playgroud)

  • 当我们可以简单地`decimal.ToString("N2")`将十进制格式化为两个地方12行代码*相比有点多*.事实是,内置的HTML帮助器/扩展应该具有格式化结果的重载. (3认同)