MVC3 HtmlHelper Tutorial not working

I am having a problem with the MVC3 MusicStore tutorial. It defines an HtmlHelper with the Truncate method. The helper is as follows:

using System.Web.Mvc;

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

In the view, I import it with @using MusicStore.Helpers, and then try to use it with<td>@Html.Truncate(item.Title, 25) </td>

However, the compiler tells me that such a method (Truncate) does not exist and seems to be looking for Truncate on IEnumerable [MvcMusicStore.Models.Album] (which is my model), and not on my HtmlHelpers class.

(NB the square brackets above are really angle brackets in my code, could not escape them)

Can someone tell me what I am doing wrong?

+3
source share
3 answers

Extension methods must be declared in a static class:

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

, , , , , :

@using System.Web.Mvc
...
<td>@Html.Truncate(item.Title, 25)</td>

, Razor using, ~/Views/web.config:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.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.Routing" />
        <add namespace="Namespace.Containig.Static.Class.With.Custom.Helpers" />
      </namespaces>
    </pages>
</system.web.webPages.razor>
+9

. :

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

, @Darin Dimitrov - MvcHtmlString.

web.config - , .

0

You may also want to add a namespace to your web.config. I know that I use my helpers on several pages. Remember that adding usingfor each view is a pain.

<system.web>
  <pages>
    <namespaces>
      <add namespace="MusicStore.Helpers"/>
    </namespaces>
  </pages>
</system.web>
0
source

All Articles