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

2

37

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.

Varion answered 12/7, 2009 at 11:14 Comment(3)
Is this 'accessing' or 'referencing'? [not picking nits - a question of transitioning from vb]Prado
@Prado what's the difference?Varion
In my mind....referencing is the act of prepping the system for the actual utilization (accessing). We can't use a method of a different class until we've setup the reference.Prado
P
50

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>
Proudlove answered 12/7, 2009 at 11:19 Comment(2)
I had to close the .aspx file in VS2008 and open the file again before Intellisense picked up the imported namespace.Sperm
Is it literally "MyProject.Extensions", or is it specific? So would mine be: <add namespace="BusinessLogic.ExtensionModule" />?Brainbrainard
I
20

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

@using MyBlogEngine;  
Instigation answered 8/10, 2012 at 20:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.