【问题标题】:My namespace is not found in MVC 5 view在 MVC 5 视图中找不到我的命名空间
【发布时间】:2015-02-12 19:55:48
【问题描述】:

我正在尝试创建自己的助手,但我完全陷入了这个错误。我已经在网上搜索并阅读了很多关于此类问题的帖子。 当我尝试将命名空间添加到视图时,我收到错误“找不到类型或命名空间'CustomHelpers'...” 所以我为我的助手创建了一个类,并将命名空间添加到 Views web.config。 我的助手类

using System.Web.Mvc;

namespace CustomHelpers
{
    public static class CustomHelpers
    {
        public static string Truncate(this HtmlHelper helper, string input, int length)
        {
            if (input.Length <= length)
            {
                return input;
            }
            else
            {
                return input.Substring(0, length) + "...";
            }
        } 
    }
}

我的 web.config

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="Playground.Web" />
    <add namespace="CustomHelpers"/>
  </namespaces>
</pages>
</system.web.webPages.razor>

我的观点

@using CustomHelpers
@{
    ViewBag.Title = "Home Page";
 }

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    问题是您不应该将类命名为与其命名空间相同的名称。

    Do not name a class the same as its namespace

    例如,

    namespace YourProjectName.Framework
    {
        public static class CustomHelpers
        {
            ...
        }
    }
    

    【讨论】:

    • 成功了!!非常感谢!! :)
    猜你喜欢
    • 2015-06-30
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 2015-04-04
    相关资源
    最近更新 更多