I would like to create a helper that can be used like
@Html.MyHelperFor(m => m.Name)
this should return for example
Following up on mattytommo's answer, this works great but there is only a small problem when used with complex objects, such as if you are using this code for a property inside an EditorTemplate.
Instead of
var data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string propertyName = data.PropertyName;
If using MVC4, you can change it to
var propertyName = helper.NameFor(expression);
or for MVC3 and below
var propertyName = expression.Body.ToString();
propertyName = propertyName.Substring(propertyName.IndexOf(".") + 1);
if (!string.IsNullOrEmpty(helper.ViewData.TemplateInfo.HtmlFieldPrefix))
propertyName = string.Format("{0}.{1}", helper.ViewData.TemplateInfo.HtmlFieldPrefix, propertyName);
Full code:
public static MvcHtmlString MyHelperFor(this HtmlHelper helper, Expression> expression, object htmlAttributes = null)
{
var propertyName = expression.Body.ToString();
propertyName = propertyName.Substring(propertyName.IndexOf(".") + 1);
if (!string.IsNullOrEmpty(helper.ViewData.TemplateInfo.HtmlFieldPrefix))
propertyName = string.Format("{0}.{1}", helper.ViewData.TemplateInfo.HtmlFieldPrefix, propertyName);
TagBuilder span = new TagBuilder("span");
span.Attributes.Add("name", propertyName);
span.Attributes.Add("data-something", propertyName);
if (htmlAttributes != null)
{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
span.MergeAttributes(attributes);
}
return new MvcHtmlString(span.ToString());
}