Expression.Compile () vs ModelMetadata.FromLambdaExpression

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

+7
lambda asp.net-mvc
source share
1 answer

These solutions are used for two different contexts.

1) Used by views to correctly prefix html fields when preparing bindings to the model and has almost nothing to do with ModelMetadata. This code will provide "Customer.Addresses [0] .City" in case you need to make a subformat.

This method applies only to PropertyInfo.Name. This will never give you the contents of the [DisplayName] attribute.

2) This is what is mainly used to work with Modelmetadata. I would use the method two 99% of the time, unless you need to solve # 1. It will also get the metadata associated with the DataAnnotations attribute. This threshold gives you the content of [DisplayName] .

+3
source share

All Articles