asp.net-mvc-4 - 当我为 UrlHelper 创建扩展方法时出现错误

标签 asp.net-mvc-4 url-rewriting

我正在使用这个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/

相关文章:

c# - 如何将具有一个键和多个值的列表绑定(bind)到 GridView 或 Repeater

asp.net-mvc - 向 ASP.NET MVC 4 中的单选按钮添加自定义类

apache - ifModule mod_rewrite 标记在 .htaccess mod_rewrite 文件中是否多余

php - Yii 框架 : Yii application in a root subfolder

c# - 无法向 CaSTLe Windsor 注册 MvcMailer

html - Bootstrap 在新创建的页面 MVC C# 中不起作用

c# - Global.asax 上的 UrlRewriting 和 SQL 输出缓存

.htaccess 检查两个位置的文件,否则抛出 404

c# - 在 MVC 的每个页面上放置重复出现的代码的正确位置是什么

iis-7 - 具有 "?"时的 IIS7 url 重写问题