问题
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)
?
回答1:
You could start by defining a custom TextHelper
:
public class TextHelper
{
public TextHelper(ViewContext viewContext)
{
ViewContext = viewContext;
}
public ViewContext ViewContext { get; private set; }
}
and then have all your methods be extension methods of this TextHelper
:
public static class TextHelperExtensions
{
public static IHtmlString MakeShortText(
this TextHelper textHelper,
string text,
int value
)
{
...
}
}
Then you could define a custom web page:
public abstract class MyWebViewPage<T> : WebViewPage<T>
{
public override void InitHelpers()
{
base.InitHelpers();
Text = new TextHelper(ViewContext);
}
public TextHelper Text { get; private set; }
}
then in your ~/Views/web.config
(not in ~/web.config
) configure this custom web page as base page for your Razor views using the pageBaseType
attribute:
<pages pageBaseType="AppName.Web.Mvc.MyWebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
and then in your views you will be able to use:
@Text.MakeShortText(Model.Text, 10)
And if you wanted to use the following syntax as shown in your question:
@Text().MakeShortText(Model.Text, 10)
simply modify the custom view engine so that Text
is not a property but a method that will return an instance of the TextHelper
. Or even return the HtmlHelper
instance so that you don't need to move your existing extension methods to TextHelper
:
public abstract class MyWebViewPage<T> : WebViewPage<T>
{
public HtmlHelper Text()
{
return Html;
}
}
The second syntax is also possible:
@Html.Text().MaksShortText(Model.Text, 10)
Simply define a custom Text()
extension for the HtmlHelper
class:
public static class HtmlExtensions
{
public static TextHelper Text(this HtmlHelper htmlHelper)
{
return new TextHelper(htmlHelper.ViewContext);
}
}
and then the same way as in the first case you would have your custom methods be extension methods of this TextHelper
class.
来源:https://stackoverflow.com/questions/9148662/creating-custom-helper-available-in-views