提取要在标签元素上使用的值?

时间:2011-02-07 18:15:49

标签: html asp.net-mvc-2 label html-helper

您好,

Label有一个for属性,例如pointe到编辑器:

<label for="ModelViewAd_Title">Titel</label>

我正在构建一个用于生成标签的自定义帮助器,此方法头看起来像这样:

public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression, Boolean showToolTip)

提取价值的最简单方法是什么?或者我是否必须手动构建for值?

BestRegards

2 个答案:

答案 0 :(得分:0)

像这样:

public static MvcHtmlString LabelFor<TModel, TValue>(
    this HtmlHelper<TModel> self, 
    Expression<Func<TModel, TValue>> expression, 
    Boolean showToolTip
)
{
    var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
    var id = self.ViewData.TemplateInfo.GetFullHtmlFieldId(metadata.PropertyName);
    // do something with the id
    ...
}

答案 1 :(得分:0)

这篇文章解决了我的问题:

http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspx

详细说明:

string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)