You can get property name easily like this:
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var propName = metadata.PropertyName;
Or you can get property and its attributes:
MemberExpression memberExpression = (MemberExpression) expression.Body;
var member = memberExpression.Member as PropertyInfo;
var attributes = member.GetCustomAttributes();
For example you can write a simple method that generates a input element like this:
public static MvcHtmlString TextboxForCustom<TModel, TResult>(this HtmlHelper<TModel> html,
Expression<Func<TModel, TResult>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var propName = metadata.PropertyName;
StringBuilder sb = new StringBuilder();
sb.AppendFormat("<input type=\"text\" id=\"{0}\" />", propName);
return MvcHtmlString.Create(sb.ToString());
}
Take a look at my answer here.
var value
, but call out the type ofm
explicitly rather than justvar m
, especially when the type ofm
is obvious? – Dorathydorca