我正在使用这个class在我的应用程序中拥有干净的 URL:
public static class UrlEncoder
{
public static string ToFriendlyUrl(this UrlHelper helper,
string urlToEncode)
{
urlToEncode = (urlToEncode ?? "").Trim().ToLower();
StringBuilder url = new StringBuilder();
foreach (char ch in urlToEncode)
{
switch (ch)
{
case ' ':
url.Append('-');
break;
case '&':
url.Append("and");
break;
case '\'':
break;
default:
if ((ch >= '0' && ch <= '9') ||
(ch >= 'a' && ch <= 'z'))
{
url.Append(ch);
}
else
{
url.Append('-');
}
break;
}
}
return url.ToString();
}
}
我正在以这种方式使用上面的类:
<a href="/Products/@item.Id/@Url.ToFriendlyUrl(item.Name)">@item.Name</a>
但我收到此错误并且扩展无法正常工作:
Compiler Error Message: CS1061: 'System.Web.Mvc.UrlHelper' does not contain a definition for 'ToFriendlyUrl' and no extension method 'ToFriendlyUrl' accepting a first argument of type 'System.Web.Mvc.UrlHelper' could be found (are you missing a using directive or an assembly reference?)
我添加了这些 using 指令:
using System;
using System.Text;
using System.Web.Mvc;
我试过this method但我仍然有同样的错误:
@UrlHelper.ToFriendlyUrl(item.Name)
并使用此指令using System.Web.Http.Routing;
而不是using System.Web.Mvc;
但我仍然有同样的错误。
看来 UrlHelper
属于另一个程序集,我不知道。
有什么想法吗?
感谢您的建议
最佳答案
您还需要在 View 中包含 UrlEncoder
类的命名空间:
@using Mynamespace
关于asp.net-mvc-4 - 当我为 UrlHelper 创建扩展方法时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19065715/