Thursday 26 July 2012

TextBoxFor and DisplayFormatAttribute


Usage

Model

[DisplayFormat(DataFormatString = "{0:0.##}", ApplyFormatInEditMode = true, NullDisplayText = "")]
public decimal? Quantity { get; set; }

View

@Html.FormattedTextBoxFor(m => m.Quantity)
 

Source

public static MvcHtmlString FormattedTextBoxFor(this HtmlHelper html, Expression<Func> expression, object htmlAttributes = null)
{
    var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
    var formatString = metadata.EditFormatString;
    if (formatString == null) return html.TextBoxFor(expression, htmlAttributes);
    var value = String.Format(formatString, metadata.Model);
    var name = ExpressionHelper.GetExpressionText(expression);
    return html.TextBox(name, value, htmlAttributes);
}