跟进 mattytommo 的回答,这很好用,但在与复杂对象一起使用时只有一个小问题,例如,如果您将此代码用于 EditorTemplate 中的属性。
代替
var data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string propertyName = data.PropertyName;
如果使用 MVC4,您可以将其更改为
var propertyName = helper.NameFor(expression);
或对于 MVC3 及以下
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);
完整代码:
public static MvcHtmlString MyHelperFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> 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());
}