1

I have a custom helper method defined in a static class like so:

namespace MyProject.Helpers
{
    public static class MyHelpers
    {
        public static MvcHtmlString TestData(this HtmlHelper helper,    Guid controlId)
        {
            return MvcHtmlString.Create(string.Format("<div>Test Data: {0}</div>", controlId.ToString()));
        }
    }
}

I'd like to use this helper within another helper that is defined as a cshtml template like so:

@using System.Web.Mvc
@using MyProject.Helpers

@helper PanelHelper(ADOR.CMSWeb.Data.CMSControl control)
{
    <div>
    @Html.TestData(Guid.NewGuid())
    </div>
}

This does not work. I don't have access to the Html helper from within the cshtml helper. I've tried using System.Web.Mvc.HtmlHelper, but my extension method isn't on that class.

Does anyone know how to access a static Helper from within a cshtml Helper to accomplish what I'm trying to do? It seems like it should be easy to do.

Thanks.

Michael Earls
  • 1,467
  • 1
  • 15
  • 25
  • No, it doesn't work. The "@Html" is not available from within the cshtml helper. – Michael Earls Mar 25 '15 at 14:48
  • 2
    Why not just add another method to your static class for `PanelHelper`?. Really, you should avoid view helpers altogether. They violate the MVC pattern, aren't compiled until runtime (meaning your code blows up live instead of during build), and are difficult to test. – Chris Pratt Mar 25 '15 at 14:50
  • Here's a related question: [link](http://stackoverflow.com/questions/6679618/using-html-inside-shared-helper-in-app-code) – Michael Earls Mar 25 '15 at 14:59

1 Answers1

1

I'm personally not a fan of @helper for this and other reasons. Changing your helper to a partial view would resolve the issue.

Another solution is to add HtmlHelper as another parameter to your PanelHelper.

Or you could create a PanelHelper extension method and use the TagBuilder to create your Html.

(I would highly recommend using TagBuilder instead of string.Format to create Html. It can create html in a stricter format and is unit-tested my Microsoft)

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • Thanks for the suggestion. I used String.Format for this simple code to show that I was actually going to use the Guid value that I passed in. I'm using TagBuilder in my other helper. – Michael Earls Mar 25 '15 at 14:58