从服务器端获取DataFormatString格式的值

时间:2015-04-08 10:45:13

标签: c# model-view-controller data-annotations displayformat

class Report
{
    [Display(Name = "Market Value")]
    [DisplayFormat(DataFormatString = "£ {0:#,##0}", ConvertEmptyStringToNull = true)]
    public int? MarketValue { get; set; }
}

当然它在视图中有效,结果是“£10,000”

@Html.DisplayFor(model => report.MarketValue)

如何通过服务器端检索格式化的值?

string formattedValue = report.MarketValue.ToFormattedString();

提前致谢!

1 个答案:

答案 0 :(得分:0)

非常粗糙,但它可以做到这一点:

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;
}

用法:

    var r = new Report
    {
        MarketValue = 10000
    };
    var formated = r.GetAttributeFormatedString(x => x.MarketValue);