What is the easiest way to get the property value from a passed lambda expression in an extension method for HtmlHelper?
Try like this:
public static MvcHtmlString Try<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression
)
{
var builder = new TagBuilder("textarea");
builder.AddCssClass("ckeditor");
builder.MergeAttribute("cols", "80");
builder.MergeAttribute("name", "editor1");
builder.MergeAttribute("id", expression.Name); // not sure about the id - verify
var value = ModelMetadata.FromLambdaExpression(
expression, htmlHelper.ViewData
).Model;
builder.SetInnerText(value.ToString());
return MvcHtmlString.Create(builder.ToString());
}
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Object value = metadata.Model;
String name = metadata.PropertyName;
I Know this is an old thread but just in case if someone is looking for it, the way to generate id / name attribute is also:
System.Web.Mvc.ExpressionHelper.GetExpressionText(expression);
I'm using this in my extensions and never had any issues with it. It also works great with nested properties.