class Report
{
[Display(Name = "Market Value")]
[DisplayFormat(DataFormatString = "£ {0:#,##0}", ConvertEmptyStringToNull = true)]
public int? MarketValue { get; set; }
}
Of course it works in the view and the result is "£ 10,000"
@Html.DisplayFor(model => report.MarketValue)
How can I retrieve the formatted value via server side with something like this?
string formattedValue = report.MarketValue.ToFormattedString();
Thanks in advance!
Very rough, but it can do the thing:
public static string GetAttributeFormatedString<TModel, TMember>(this TModel model, Expression<Func<TModel, TMember>> memberSelector)
{
var selectorBody = memberSelector.Body;
if (selectorBody.NodeType != ExpressionType.MemberAccess)
{
throw new ArgumentException("Nope dude, not this time", "memberSelector");
}
var attribute = ((MemberExpression) selectorBody).Member
.GetCustomAttributes(typeof(DisplayFormatAttribute), true)
.OfType<DisplayFormatAttribute>()
.FirstOrDefault();
if (attribute == null)
{
throw new InvalidOperationException("Attribute, dude");
}
var format = attribute.DataFormatString;
var result = string.Format(format, memberSelector.Compile().Invoke(model));
return result;
}
Usage:
var r = new Report
{
MarketValue = 10000
};
var formated = r.GetAttributeFormatedString(x => x.MarketValue);