I'd want to refactor this code to get rid of relying on TModel, TValue
public static string DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
// null checks
DescriptionAttribute descriptionAttribute = null;
if (expression.Body is MemberExpression memberExpression)
{
descriptionAttribute = memberExpression.Member
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.Cast<DescriptionAttribute>()
.SingleOrDefault();
}
return descriptionAttribute?.Description ?? string.Empty;
}
which has invocation like that:
@Html.DescriptionFor(x => x.MyModel.MyOtherModel.Property)
to something like that
public static string DescriptionFor2<T>(Expression<Func<T>> expression)
{
if (expression == null)
throw new ArgumentNullException(nameof(expression));
if (!(expression.Body is MemberExpression memberExpression))
{
return string.Empty;
}
foreach (var property in typeof(T).GetProperties())
{
if (property == ((expression.Body as MemberExpression).Member as PropertyInfo))
{
var attr = property
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.Cast<DescriptionAttribute>()
.FirstOrDefault();
return attr?.Description ?? string.Empty;
}
}
return string.Empty;
}
with invocation like that:
@MyHtml.DescriptionFor2<MyOtherModel>(x => x.MyProperty);
But here's error:
Delegate 'Func' does not take 1 arguments