Create CheckboxFor MVC helper with title attribute from model description

后端 未结 2 1580
陌清茗
陌清茗 2021-01-20 07:26

I\'ve created a text box helper to add a title (tooltip) taken from the description attribute for the field in a model:

 public static MvcHtmlString TextBoxF         


        
2条回答
  •  庸人自扰
    2021-01-20 07:50

    I tried and it seems to work so far - still have to try a few examples where I need the ID of the element:

     public static MvcHtmlString CheckBoxForWithTitle(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes = null)
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            string chkboxText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();
            MemberExpression memberExpression = expression.Body as MemberExpression;
            string parameterName = memberExpression.Member.Name;
    
            if (string.IsNullOrEmpty(chkboxText))
                return MvcHtmlString.Empty;
            var chkbox = new TagBuilder("input");
            chkbox.Attributes.Add("type", "checkbox");
            chkbox.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            if (!string.IsNullOrEmpty(metaData.Description))
                chkbox.Attributes.Add("title", metaData.Description);
            return MvcHtmlString.Create(chkbox.ToString());
        }
    

提交回复
热议问题