Custom MVC HTML Helper Namespace

how can i create something like this: Html.MyApp.ActionLink ()? Thanks.

+4
source share
1 answer

You cannot do this. The only way to add Html to the class is with the extension method. You cannot add the “Extension Properties” that you will need to use Html.MyApp . Closest you can come is Html.MyApp().Method(...)

It’s best to either include them as extension methods in Html, or completely create a new class (for example, MyAppHtml.Method(...) or MyApp.Html.Method(...) ). Recently there was a blog post specifically showing the "Html5" class with these methods, but unfortunately my Google skills are failing me and I cannot find it :(

Added October 13, 2011, as asked in the comment

To do something like Html.MyApp().ActionLink() , you need to create an extension method on HtmlHelper that returns an instance of the 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 will need to import the namespace in which this class is located in Web.config , for example:

 <?xml version="1.0"?> <configuration> <system.web.webPages.razor> <pages> <namespaces> <add namespace="MyHelper"/> </namespaces> </pages> </system.web.webPages.razor> </configuration> 
+7
source

Source: https://habr.com/ru/post/1340470/


All Articles