【问题标题】:Extracting for value to use on label element?提取值以在标签元素上使用?
【发布时间】:2023-12-29 03:46:02
【问题描述】:

嗨,

标签有一个指向编辑器的 for 属性,例如:

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

我正在构建一个自定义助手来生成标签,这个方法头看起来像这样:

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

为了获得价值,最简单的方法是什么?还是我必须手动构建 for 值?

致以最诚挚的问候

【问题讨论】:

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


    【解决方案1】:

    像这样:

    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
        ...
    }
    

    【讨论】:

    • 这只会让我得到最后一部分,例如标题而不是 ModelViewAd_Title?
    • 你在使用 EditorTemplates 吗?
    • 我正在使用 html 助手,例如 html.TextBoxFor 但不是 html.EditorFor
    【解决方案2】:

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

    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)
    

    【讨论】: