【问题标题】:MVC 4 and Extension Methods with RazorMVC 4 和带有 Razor 的扩展方法
【发布时间】:2012-08-30 10:16:16
【问题描述】:

我创建了一个扩展方法并将其命名空间包含在我的web.config 文件中。扩展方法工作正常,测试代码可以正常访问。问题是,我仍然收到与未找到命名空间有关的错误。

我收到的 ASP .NET 错误消息是:

CS1061:“System.Uri”不包含“IsCurrentUrl”的定义,并且找不到接受“System.Uri”类型的第一个参数的扩展方法“IsCurrentUrl”(您是否缺少 using 指令或程序集参考?)

下面是相应的代码。

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>
}

【问题讨论】:

  • 视图文件中的using语句是否正确?
  • 没有。我将命名空间放在 web.config 中,这样我就不必为每个视图文件都这样做了。
  • 你试过改成MyMainSite2.Library.Extensions.UriExtensions吗?
  • 你有什么想改变的想法?
  • 您将命名空间添加到哪个 Web 配置文件?视图还是主视图?

标签: c# asp.net-mvc razor


【解决方案1】:

petro.sidlovskyy 给出了答案。

我将命名空间添加到主 Web.config 而不是视图的 Web.config。

当我在Views文件夹的Web.config中添加命名空间时,该命名空间被视图识别,问题就解决了。

【讨论】:

    【解决方案2】:

    我只想发帖说,我已经有这个问题好几个月了,我按照 ASP.NET 网站上的指南逐行操作,我能够为 Razor 恢复 Intellisense文件。

    这里是链接:http://www.asp.net/mvc/overview/releases/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

    我希望这有助于防止其他人也掉头发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-28
      • 2023-03-18
      • 2013-07-17
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多