Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use an extension method in an ASP.NET MVC View?

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.

like image 396
pupeno Avatar asked Jul 12 '09 11:07

pupeno


People also ask

What is extension method in ASP NET MVC?

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.

How do you call an extension method?

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.

What is used of extension methods and how do you create and use it?

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.

Where do you put extension methods?

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.


2 Answers

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> 
like image 142
eu-ge-ne Avatar answered Oct 09 '22 08:10

eu-ge-ne


For pages using Razor / WebPages, you can include a using directive in your .cshtml page.

@using MyBlogEngine;   
like image 45
p.campbell Avatar answered Oct 09 '22 07:10

p.campbell