josecortesp
josecortesp

Reputation: 1576

ASP.NET MVC html helpers not working

I hope somebody can help me. I've been trying to write a custom html helper for my MVC application. First at all, i tried with a testing one, which only writes a

tag for the specified param. The things is, it does not work unless I explicitly import the namespace. I've been reading a lot and as i read, That method should appear without the import namespace like this:

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

But this method, Prueba, is not showing up in the VS Intellisense.

My Class is the following:

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

}

Thanks in advance!

Upvotes: 6

Views: 12138

Answers (3)

user1752532
user1752532

Reputation:

For some reason in visual studio 2013 you have to restart vs in order for changes in the web.config to be applied.

Upvotes: 7

Robert Koritnik
Robert Koritnik

Reputation: 105029

Namespace must be declared/imported somewhere. You can do that either:

  • within the page itself
  • master page or
  • inside web.config file

If you want something global it's best to configure your namespace in web.config.

Use <@import...> directive for the first two and <namespace> configuration element for the last one.

Upvotes: 13

Jere.Jones
Jere.Jones

Reputation: 10123

You can add the namespace to the web.config and then you won't have to worry about it later.

Inside your web.config, you should see something like this:

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

Just add a line with your namespace.

If you don't want the helpers to be globally imported, each directory can have it's own web.config. Unless specifically set, those "sub" web.configs will inherit settings from higher web.configs. If you go this route, be forewarned, some settings can only be set at the application level. It can get confusing fast.

Upvotes: 6

Related Questions