Hi folks! There is a common issue to write strongly-typed Html helpers. The problem is how to retrieve property name/value pair. Assume we have following Html helper declaration:
public static string DatePickerFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, DateTime?>> expression)
There are several solutions I found: 1.
var value = expression.Compile()( helper.ViewData.Model );
string name = ExpressionHelper.GetExpressionText( expression );
string fullName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName( name );
2.
ModelMetadata metadata = ModelMetadata.FromLambdaExpression( expression, helper.ViewData );
Object value = metadata.Model;
String name = metadata.PropertyName;
3. getting member name only using MemberExpression
string GetPropertyName<T>(Expression<Func<T>> property)
{
var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
if (propertyInfo == null)
{
throw new ArgumentException("The lambda expression 'property' should point to a valid Property");
}
return propertyInfo.Name;
}
All of them have different implementation from the first look (used Reflector to investigate) but I didn't dig deeply into.
I've stuck with so many ways to resolve issue and would like to know which solution is BETTER for different situations and WHY?
I'll be appreciate for any help