how I can create something like this: Html.MyApp.ActionLink()? Thanks.
-
In that context, what is MyApp? A type? A local object? A controller? A route? A view? What?Marc Gravell– Marc Gravell2011-02-19 19:28:45 +00:00Commented Feb 19, 2011 at 19:28
-
I would like to have a root for all of my helpers. So instead to have helpers like Html.MyHelperForLinks or Html.MyHelperForText, I want this: Html.MyApp.MyHelperForLinks, Html.MyApp.MyHelperForText, Html.MyApp.MyHelperForTextBox, and so on...Luca CB– Luca CB2011-02-20 06:48:43 +00:00Commented Feb 20, 2011 at 6:48
1 Answer
You can't do this. The only way you can add to the Html class is via an extension method. You cannot add "Extension Properties", which is what would be required for you to use Html.MyApp. The closest you could come is Html.MyApp().Method(...)
Your best bet is probably to either include them as extension methods on Html, or create a new class completely (eg. MyAppHtml.Method(...) or MyApp.Html.Method(...)). There was a blog post around recently specifically showing an "Html5" class with these methods, but unfortunately my Google skills are failing me, and I can't find it :(
Added 13 Oct 2011 as asked in comment
To do something like Html.MyApp().ActionLink() you need to create an extension method on HtmlHelper, that returns an instance of a class with your custom method:
namespace MyHelper
{
public static class MyHelperStuff
{
// Extension method - adds a MyApp() method to HtmlHelper
public static MyHelpers MyApp(this HtmlHelper helper)
{
return new MyHelpers();
}
}
public class MyHelpers
{
public IHtmlString ActionLink(string blah)
{
// Wrap the html in an MvcHtmlString otherwise it'll be HtmlEncoded and displayed to the user as HTML :(
return new MvcHtmlString(string.Format("<a href=\"#\">{0}</a>", HttpUtility.HtmlEncode(blah)));
}
}
}
Note: You'll need to import the namespace this class is in in Web.config, like this:
<?xml version="1.0"?>
<configuration>
<system.web.webPages.razor>
<pages>
<namespaces>
<add namespace="MyHelper"/>
</namespaces>
</pages>
</system.web.webPages.razor>
</configuration>
The change in the Web.Config file needs to be done in the config file for the view, not the global one