-1
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();

提前致谢!

4

1 回答 1

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);
于 2015-04-08T11:49:08.497 回答