There is a common problem for writing highly typed HTML helpers. The problem is how to get the name / value pair of the property. Suppose we follow the declaration of the html helper:
public static string DatePickerFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, DateTime?>> expression)
There are several solutions that I have 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. Get Member Name Using MemberExpression Only
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 implementations at first glance (a reflector is used for research), but I did not delve deeply.
I have tied up so many ways to solve the problem and would like to know which solution is BETTER for different situations and WHY?
I would be grateful for any help
lambda asp.net-mvc
Cheburek
source share