I would like to create a helper that can be used like
@Html.MyHelperFor(m => m.Name)
this should return for example
You can use the FromLambaExpression method from ModelMetadata like this:
namespace System.Web.Mvc.Html
{
public static class CustomHelpers
{
public static MvcHtmlString MyHelperFor(this HtmlHelper helper, Expression> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
var name = metaData.PropertyName;
// create your html string, you could defer to DisplayFor to render a span or
// use the TagBuilder class to create a span and add your attributes to it
string html = "";
return new MvcHtmlString(html);
}
}
}
The ModelMetadata class is in the System.Web.Mvc namespace. The FromLambdaExpression method is what the built in helpers use so then you can be sure your helper will function the same as the built in helpers. By placing the CustomHelpers class inside the System.Web.Mvc.Html namespace you can then access your helper like you would the other helpers, i.e. @Html.MyHelperFor().