Reputation: 209
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?
Upvotes: 3
Views: 4796
Reputation: 1039488
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>
Upvotes: 9
Reputation: 31761
You may also want to consider adding the namespace to your web.config. I know I use my helpers on multiple pages. Remembering to add using
on every view is a pain.
<system.web>
<pages>
<namespaces>
<add namespace="MusicStore.Helpers"/>
</namespaces>
</pages>
</system.web>
Upvotes: 0
Reputation: 15900
Extension methods must be defined in a static class. So change you code to:
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) + "...";
}
}
}
Also, @Darin Dimitrov brings up a good point - you should really retrun an instance of MvcHtmlString
.
On a related note, you can import namespaces into your views through the web.config - I'd recommend doing that so you don't have to remember to do it in every page.
Upvotes: 0