Creating custom Html Helper: MyHelperFor

前端 未结 4 1773
北海茫月
北海茫月 2020-12-14 04:40

I would like to create a helper that can be used like

@Html.MyHelperFor(m => m.Name)

this should return for example

4条回答
  •  伪装坚强ぢ
    2020-12-14 05:23

    Following up on mattytommo's answer, this works great but there is only a small problem when used with complex objects, such as if you are using this code for a property inside an EditorTemplate.

    Instead of

    var data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
    string propertyName = data.PropertyName;
    

    If using MVC4, you can change it to

    var propertyName = helper.NameFor(expression);
    

    or for MVC3 and below

    var propertyName = expression.Body.ToString();
    propertyName = propertyName.Substring(propertyName.IndexOf(".") + 1);
    if (!string.IsNullOrEmpty(helper.ViewData.TemplateInfo.HtmlFieldPrefix))
        propertyName = string.Format("{0}.{1}", helper.ViewData.TemplateInfo.HtmlFieldPrefix, propertyName);
    

    Full code:

        public static MvcHtmlString MyHelperFor(this HtmlHelper helper, Expression> expression, object htmlAttributes = null)
        {
            var propertyName = expression.Body.ToString();
            propertyName = propertyName.Substring(propertyName.IndexOf(".") + 1);
            if (!string.IsNullOrEmpty(helper.ViewData.TemplateInfo.HtmlFieldPrefix))
                propertyName = string.Format("{0}.{1}", helper.ViewData.TemplateInfo.HtmlFieldPrefix, propertyName);
    
            TagBuilder span = new TagBuilder("span");
            span.Attributes.Add("name", propertyName);
            span.Attributes.Add("data-something", propertyName);
    
            if (htmlAttributes != null)
            {
                var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
                span.MergeAttributes(attributes);
            }
    
            return new MvcHtmlString(span.ToString());
        }
    

提交回复
热议问题