ASP.NET MVC html助手无法正常工作

时间:2009-09-15 05:37:42

标签: c# asp.net-mvc html-helper

我希望有人可以帮助我。 我一直在尝试为我的MVC应用程序编写一个自定义的html助手。首先,我尝试了一个测试版,它只为指定的参数写了一个

标签。 事情是,除非我显式导入命名空间,否则它不起作用。 我一直在阅读,当我读到时,该方法应该没有像这样的导入命名空间:

<%=Html.Prueba("This is a paragraph") %>

但是这种方法Prueba没有出现在VS Intellisense中。

我的班级如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace EasyGoCostaRica.Helpers
{
    public static class ViewsHelpers
    {
        //This method is just for testing. Is not working :(
        public static string Prueba(this HtmlHelper helper, string param1)
        {
            return string.Format("<p>{0}</p>", param1);
        }
    }

}

提前致谢!

3 个答案:

答案 0 :(得分:12)

命名空间必须声明/导入某处。你也可以这样做:

    页面内
  • 母版页或
  • 在web.config文件中

如果你想要一些全局,最好在web.config中配置命名空间。

对前两个使用<@import...>指令,对最后一个使用<namespace>配置元素。

答案 1 :(得分:6)

您可以将命名空间添加到web.config中,然后您不必再担心它。

在你的web.config中,你应该看到如下内容:

<namespaces>
<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.Linq"/>
<add namespace="System.Collections.Generic"/>
</namespaces>

只需在命名空间中添加一行。

如果您不希望全局导入帮助程序,则每个目录都可以拥有自己的web.config。除非特别设置,否则那些“sub”web.configs将继承更高web.configs的设置。如果你走这条路线,要预先警告,一些设置只能在应用程序级别设置。它可能会很快混淆。

答案 2 :(得分:6)

出于某种原因,在visual studio 2013中,您必须重新启动vs才能应用web.config中的更改。