时间:2011-01-06 16:51:54

标签: c# asp.net-mvc format

6 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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>

希望得到这个帮助。

答案 2 :(得分:10)

答案 3 :(得分:3)

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

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

DataFormatString描述了您所需的显示格式,而ApplyFormatInEditMode标志表示您也想在可编辑模式下应用此格式(并且不仅仅是在只读模式下,这是如果你省略这个。)

(另见DisplayFormatAttribute Class

答案 4 :(得分:0)

答案 5 :(得分:0)

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

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