13

I'm following the MVC Music Store tutorial, but I've just gotten a bit stuck with the Html Helper in part 5: Part 5.

I seem to have followed it correctly so far (please correct me if I'm wrong :) )...however I am getting the following error:

'musicStoreMVC.Helpers.HtmlHelper': static types cannot be used as parameters

Here is the code from my application:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

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

If anyone can see what I'm doing wrong, or if more info is needed, I'd be grateful for the pointers!! Thanks.

tereško
  • 58,060
  • 25
  • 98
  • 150
109221793
  • 16,477
  • 38
  • 108
  • 160

5 Answers5

15

Just rename your static HtmlHelper class to HtmlHelperExtensions.

Victor Haydin
  • 3,518
  • 2
  • 26
  • 41
  • 1
    Same problem but is not working for me. I want to extend `Microsoft.VisualStudio.TestTools.UnitTesting.Assert`. Changing the class name to anything also produce the same error... – CallMeLaNN Jul 14 '11 at 01:57
  • 3
    Got it, because extension methods cannot be added to `static class` http://stackoverflow.com/questions/249222/can-i-add-extension-methods-to-an-existing-static-class – CallMeLaNN Jul 14 '11 at 02:58
1

You got a name conflict - the one static HtmlHelper that you declare in the example code and the System.Web.Mvc.HtmlHelper which is the class that you actually want to create the extension method for. Just rename your class to HtmlHelpers (as it is in the linked tutorial). The way it is right now, you are trying to implement an extension method on the static class which supposedly does not work.

hangy
  • 10,765
  • 6
  • 43
  • 63
1

It's because you're naming your extension class HtmlHelper. In truncate, you then try to add a extension method to a static class, which you cannot.

A simple solution is to rename your HtmlHelper to something different.

alexn
  • 57,867
  • 14
  • 111
  • 145
1

The this HtmlHelper helper says that Truncate() should act as if it were an instance method on HtmlHelper, but you've declared HtmlHelper as a static class, which can't have instances.

If what you're trying to do is create an extension method on a different HtmlHelper class, then as others have suggested, rename this static class. If you just need the static method, get rid of the this HtmlHelper helper parameter. You're not using it anyway.

David Moles
  • 48,006
  • 27
  • 136
  • 235
0

Delete the using part

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

and add

using System.Web.Mvc;
Cheng
  • 1,169
  • 2
  • 8
  • 8