Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Tutorial HtmlHelper not working

I'm having a problem with the MVC3 MusicStore tutorial. It defines an HtmlHelper with a Truncate method. The helper looks like this:

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 using @using MusicStore.Helpers, and then try to use it with <td>@Html.Truncate(item.Title, 25) </td>

However the compiler tells me no such method (Truncate) exists, and seems to be looking for Truncate on IEnumerable[MvcMusicStore.Models.Album] (which is my model) rather than on my HtmlHelpers class.

(NB the square brackets above are really angled brackets in my code, couldnt escape them)

Can anyone tell me what I'm doing wrong please?

like image 528
Richard Avatar asked Feb 10 '26 15:02

Richard


1 Answers

Extension methods should 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) + "...";
    }
}

and then in your view make sure you have referenced the namespace containing the static class with the extension method:

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

or if you want the helper to be available in all Razor views without the need of adding a using directive you could add the corresponding namespace to the namespaces section of ~/Views/web.config file:

<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>
like image 114
Darin Dimitrov Avatar answered Feb 12 '26 15:02

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!