I am trying to create a custom HtmlHelper that displays a numeric value formatted to a given number of decimal places. My idea is to change the ModelMetadata.DataFormatString property to achieve this. Is it possible to modify the Metadata properties in this way for a model property? How do I do it? My attempt (below) does not format the number as required.
public static MvcHtmlString FormattedNumberDisplayFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, decimal?>> expression, byte decimalPlaces)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string format = string.Format("{{0:f{0}}}", decimalPlaces);
metadata.DisplayFormatString = format;
return html.DisplayFor(expression);
}
I can of course get the formatted value out a different way in the same HtmlHelper, but I am particularly interested to know if it is possible to tweak the model metadata dynamically at run time.