我想添加一個擴展方法到我的MVC 2項目沒有成功,經過幾個小時的谷歌搜索和看這裏我很茫然。我創建了一個全新的MVC 2項目,以確保我的現有項目沒有任何不尋常之處,而且我仍面臨同樣的問題。我敢肯定,這是我「無法看到樹林的森林」的情況,所以任何幫助將不勝感激。這是擴展方法的代碼。UrlHelper擴展方法不起作用
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);
}
}
}
,這裏是在視圖中(默認情況下,一個新的MVC 2項目創建標準的家庭索引視圖)
<%@ 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>
在設計模式,當我輸入UrlHelper,智能感知不顯示的代碼我的擴展方法形象,如果我跑的項目,我得到以下錯誤:
CS0117: 'System.Web.Mvc.UrlHelper' does not contain a definition for 'Image'
起初我還以爲是那麼簡單,不添加引用(import語句),但不會出現是這樣的。對我來說真的很奇怪的是,我可以在同一個項目中將擴展方法添加到HtmlHelper對象中,而不會出現問題。
在此先感謝您提供的任何幫助。
我有沒有嘗試在一天中一個非常繁忙的測試,建立沒有立即的解決方案......但你試過重命名的輔助函數到顯然比「Image」更不常見/更明顯的東西......也許是「MyImage」或「TestImage」來查看結果是否不同? – JcMaltaDev 2010-07-31 13:02:39