我已经创建了一个扩展方法,并已纳入了我的web.config
文件的命名空间。扩展方法工作正常,并由测试代码加以确认。问题是,我仍然收到有关未找到命名空间的错误。MVC 4和扩展方法用剃刀
我正的ASP .NET错误信息是:
CS1061:“的System.Uri”不包含关于“IsCurrentUrl”和没有扩展方法的定义“IsCurrentUrl”接受类型的第一个参数'System.Uri'可以找到(你是否缺少使用指令或装配参考?)
下面是各自的代码。
Web.config文件:
<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<pages>
<namespaces>
<add namespace="System.Web" />
<add namespace="System.Web.Helpers" />
<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.Web.WebPages" />
<add namespace="MyMainSite2.Library.Extensions" />
</namespaces>
</pages>
</system.web>
扩展方法代码:
namespace MyMainSite2.Library.Extensions
{
public static class UriExtensions
{
#region Public Static Methods
public static bool IsCurrentUrl(this Uri uri, string url)
{
if (String.IsNullOrWhiteSpace(url))
return false;
url = url.Trim().ToLower();
string absolutePath = uri.AbsolutePath.Trim().ToLower();
if (!url.StartsWith("/") && absolutePath.StartsWith("/"))
absolutePath = absolutePath.Remove(0, 1);
bool match = absolutePath == url;
return match;
}
#endregion
}
}
剃刀代码:
@model MyMainSite2.UI.Web.Models.Shared.TopMenuModel
@foreach (var item in this.Model.Items)
{
if(this.Request.Url.IsCurrentUrl(item.Url)) // this line is failing because UriExtensions.IsCurrentUrl is not being found
{
@:<li class="current">
}
else
{
@:<li>
}
@:<a href="@item.Url">@item.Text</a></li>
}
你有没有在视图文件中使用正确的声明? – dtsg
不,我将命名空间放在web.config中,这样我就不必为每个视图文件执行此操作。 – rhughes
您是否尝试将其更改为'MyMainSite2.Library.Extensions.UriExtensions'? – dtsg