从服务器端获取 DataFormatString 格式化值
Get DataFormatString formatted value from server side
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();
提前致谢!
很粗糙,但是可以做到:
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);
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();
提前致谢!
很粗糙,但是可以做到:
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);