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

属性:

public decimal Cost { get; set; }

html助手:

m.Cost)%>

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

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

 public static MvcHtmlString DecimalBoxFor( this HtmlHelper helper, TEntity model, Expression> 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")%> 

我已经稍微调整了Jamiec的答案,以便(a)使其编译并且(b)使用与框架相同的基础方法:

 public static MvcHtmlString DecimalBoxFor(this HtmlHelper html, Expression> 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); } 

我推荐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 
@Html.DisplayFor(m=>m.Cost)
@Html.EditorFor(m=>m.Cost)
// rendering html
12.34

希望这有帮助。

所描述问题的解决方案非常简单:您只需将以下属性应用于已解决的模型类属性:

 [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:0.00}")] public decimal Cost { get; set; } 

DataFormatString描述了您所需的显示格式,而ApplyFormatInEditMode标志表示您也希望在可编辑模式下应用此格式(而不仅仅是在只读模式下,如果省略这种情况就是这种情况)。

(另请参见DisplayFormatAttribute类 )

我不认为有一种方法可以使用HTML帮助程序,但是您可以发送预先格式化为2位小数精度的文本框的值。

如果使用For方法不是必须的,你可以这样做。

 <%: Html.TextBox("Cost", Model.Cost.ToString("N2")) %>