亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

工具提示 Html 助手

工具提示 Html 助手

C#
鳳凰求蠱 2021-11-28 20:21:52
我正在嘗試構建一個 HTML 助手,它將像HTML.ForLabel助手一樣工作,但會將標題屬性設置為[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 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

問題是因為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與標簽合并。


查看完整回答
反對 回復 2021-11-28
  • 1 回答
  • 0 關注
  • 212 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號