问题
I'm trying to add an extension method to my MVC 2 project without success and after several hours of googling and looking here I'm at a loss. I've created a brand new MVC 2 project to make sure there was not anything weird about my existing project and I'm still facing the same problem. I'm sure this is a situation of I "can't see the forest for the trees" so any help would be greatly appreciated. Here is the code for the extension method.
using System.Web.Mvc;
namespace ExtensionTest.Helper
{
public static class UrlExtensions
{
public static string Image(this UrlHelper helper, string fileName)
{
return helper.Content("~/Content/Images/" + fileName);
}
}
}
and here is the code in the view (standard home index view created by default for a new MVC 2 project)
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="ExtensionTest.Helper" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%= UrlHelper.Image("test") %>
<h2><%: ViewData["Message"] %></h2>
<p>
To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>
</asp:Content>
In design mode, when I type UrlHelper, intellisense does not show my extension method Image and if I run the project I get the following error:
CS0117: 'System.Web.Mvc.UrlHelper' does not contain a definition for 'Image'
At first I thought it was as simple as not adding a reference (Import statement), but that does not appear to be the case. The really weird thing to me is that I can add extension methods to the HtmlHelper object without issue in this same project.
Thanks in advance for any help provided.
回答1:
Extension methods in .NET should be invoked on an object instance and not on the class itself (even though they are static).
So instead of:
<%= UrlHelper.Image("test") %>
try:
<%= Url.Image("test") %>
来源:https://stackoverflow.com/questions/3378180/urlhelper-extension-method-not-working