工具提示HTML帮助器

时间:2018-08-15 15:16:17

标签: c# asp.net asp.net-mvc

我正在尝试构建一个HTML帮助程序,其功能类似于HTML.ForLabel帮助程序,但会将title属性设置为[Display]批注中的description值。我的工具提示部分有效,但我无法使htmlAttributes正常工作。

这是我给助手的代码

public static class LabelWithTooltip
{

    public static MvcHtmlString Tooltip<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
    {
        var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);

        string htmlFieldName = ExpressionHelper.GetExpressionText(expression);

        string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();

        if (String.IsNullOrEmpty(labelText))
        {
            return MvcHtmlString.Empty;
        }

        var label = new TagBuilder("label");

        label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));

        if (!string.IsNullOrEmpty(metaData.Description))
        {
            label.Attributes.Add("title", metaData.Description);
            label.MergeAttributes(htmlAttributes);
        }

        label.SetInnerText(labelText);
        return MvcHtmlString.Create(label.ToString());
    }
}

这是在视图中调用它的行

@Html.Tooltip(model => model.Guid, htmlAttributes: new { @class = "control-label col-md-2" })

它没有采用我为htmlAttributes传递的值

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

问题是因为htmlAttributes是一个匿名对象,因此需要将其作为object而不是字典进行传递。之后,您可以使用HtmlHelper.AnonymousObjectToHtmlAttributes()退还您需要与TagBuilder合并的字典。

赞:

public static MvcHtmlString Tooltip<TModel, TValue>(
    this HtmlHelper<TModel> helper, 
    Expression<Func<TModel, TValue>> expression, 
    object htmlAttributes) // Note the signature change.
{
    // ... snip

    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
    label.MergeAttributes(attributes);

    // ... snip
}

这将正确地将htmlAttributes与标签合并。