I have too much text utility methods, like MakeShortText(string text, int length), RemoveTags(string text), TimeAgo(DateTime date) and other.
I want to access them from separate helper like in next example:
@Text().MakeShortText(Model.Text, 10)
Is it possible to create such extension? Or I have to make extension for HtmlHelper like this:
@Html.Text().MaksShortText(Model.Text, 10)
?
You could start by defining a custom
TextHelper:and then have all your methods be extension methods of this
TextHelper:Then you could define a custom web page:
then in your
~/Views/web.config(not in~/web.config) configure this custom web page as base page for your Razor views using thepageBaseTypeattribute:and then in your views you will be able to use:
And if you wanted to use the following syntax as shown in your question:
simply modify the custom view engine so that
Textis not a property but a method that will return an instance of theTextHelper. Or even return theHtmlHelperinstance so that you don’t need to move your existing extension methods toTextHelper:The second syntax is also possible:
Simply define a custom
Text()extension for theHtmlHelperclass:and then the same way as in the first case you would have your custom methods be extension methods of this
TextHelperclass.