How do I access an extension method in an ASP.Net MVC View? In C# I do
using MyProject.Extensions;
and I remember seeing an XML equivalent to put in a view, but I can't find it anymore.
Perhaps the best example of extension methods are HtmlHelper extensions used in ASP.NET MVC. Extension methods are static methods of static class and they use "this" keyword in argument list to specify the type they extend. The following demo shows how to build extension method that returns word count in string.
To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
An Extension Method should be in the same namespace as it is used or you need to import the namespace of the class by a using statement. You can give any name of for the class that has an Extension Method but the class should be static.
In View:
<%@ Import Namespace="MyProject.Extensions" %>
Or in web.config (for all Views):
<pages> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Linq" /> <add namespace="System.Collections.Generic" /> <add namespace="MyProject.Extensions" /> </namespaces> </pages>
For pages using Razor / WebPages, you can include a using
directive in your .cshtml page.
@using MyBlogEngine;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With