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

16,360

Solution 1

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>

Solution 2

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

@using MyBlogEngine;  
Share:
16,360
pupeno
Author by

pupeno

You can find my blog at https://pupeno.com where I publish about coding and other stuff.

Updated on June 07, 2022

Comments

  • pupeno
    pupeno about 2 years

    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.

  • Frode Lillerud
    Frode Lillerud over 14 years
    I had to close the .aspx file in VS2008 and open the file again before Intellisense picked up the imported namespace.
  • Jonathan
    Jonathan over 11 years
    Is it literally "MyProject.Extensions", or is it specific? So would mine be: <add namespace="BusinessLogic.ExtensionModule" />?