Creating custom Html Helper: MyHelperFor

前端 未结 4 1781
北海茫月
北海茫月 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:20

    You can use the FromLambaExpression method from ModelMetadata like this:

    namespace System.Web.Mvc.Html
    {
        public static class CustomHelpers
        {
            public static MvcHtmlString MyHelperFor(this HtmlHelper helper, Expression> expression)
            {
                var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
                var name = metaData.PropertyName;
                // create your html string, you could defer to DisplayFor to render a span or
                // use the TagBuilder class to create a span and add your attributes to it
                string html = "";
                return new MvcHtmlString(html);
            }
        }
    }
    

    The ModelMetadata class is in the System.Web.Mvc namespace. The FromLambdaExpression method is what the built in helpers use so then you can be sure your helper will function the same as the built in helpers. By placing the CustomHelpers class inside the System.Web.Mvc.Html namespace you can then access your helper like you would the other helpers, i.e. @Html.MyHelperFor().

提交回复
热议问题