Html Helper not working

Jan 11, 2011 at 4:02 PM
Edited Jan 11, 2011 at 4:02 PM

I don't get the Truncate when typing "Html." What could be the problem?

<td><%: Html.Truncate(item.Title, 25) %></td>


Jan 11, 2011 at 5:44 PM

Can you verify that you've correctly added the namespace as indicated on page 67, and that the namespace exactly matches the one used for the helper on page 66 (including capitalization)?

Jan 12, 2011 at 8:13 AM
Edited Jan 12, 2011 at 8:17 AM

I made it work by doing this:

<%: HtmlHelpers.Truncate(item.Title, 25) %>

Is that correct? As you can see, I don't have a HTML class with Truncate method. I instead have HtmlHelpers class with a Truncate method 

that was receiving three parameters and I had to change to two parameters in order for this to work properly. 

Feb 16, 2011 at 8:45 PM
Edited Feb 16, 2011 at 10:20 PM

I had same problem as you mentioned.

 I fixed my problem by deleting all the "using statements" then put "using System.Web.Mvc;" in HtmlHelpers.cs



Feb 25, 2011 at 7:31 AM

Glad that worked for you, Kevin. I will move that to use the new Razor helper syntax for the next release, which should make this simpler.

Mar 5, 2011 at 12:11 PM
Edited Mar 5, 2011 at 1:01 PM

Since the HtmlHelper isn't actually used in the Truncate implementation, it should be a string extension:

namespace MvcMusicStore.Helpers {
	public static class StringHelpers {
		public static string Truncate(this string inputint length) {
			if ( input != null && input.Length > length )
				return input.Substring(0, length) + "...";
				return input;
Then the code in question becomes:
Mar 25, 2011 at 7:42 AM

@Aldo - A string extension will work, but the goal for the tutorial's sake was to show how to create a custom HTML Helper. You can create a string extension, but the advantage of writing an HTML Helper is that it's more discoverable within the view.

Mar 25, 2011 at 7:44 AM

I wrote up some additional info on HTML Helpers based on some common questions here:

I'll probably move to Razor HTML Helper syntax for the next release, since they're a little easier to set up and use.

Apr 6, 2011 at 10:25 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.