Pass HtmlHelper instance to another method MVC3 wi

2019-07-17 08:02发布

问题:

Ok I have created the following two methods. The first one is an extension method on HtmlHelper. The second one gets passed that instance of the helper and it makes the checkboxes. My actual example has nothing to do with checkboxes, this was just the easiest way to explain my issue.

public static MvcHtmlString MakeBoxGroup(this HtmlHelper<T> Html, List<string> names)
{
    string outStr = "";
    foreach(string name in names)
        outStr += MakeBox(Html, name);

    return new MvcHtmlString(outStr);
}

public static MvcHtmlString MakeBox(HtmlHelper<T> Html, string name)
{
    return Html.CheckBox(name);
}

My Question: When I try this it tells me that the HtmlHelper class doesn't implement CheckBox or any of those types of helpers. Anyone know how to pass the correct instance of the HtmlHelper down? I'm assuming I'm just using the wrong type here, but I'm not sure.

回答1:

Here you go .Checkbox are in System.Web.Mvc.Html namespace in static class InputExtensions.

    using System.Web.Mvc.Html;

    public static MvcHtmlString MakeBoxGroup(this HtmlHelper Html, List<string> names)
    {
        string outStr = "";            
        foreach (string name in names)
            outStr += MakeBox(Html, name);

        return new MvcHtmlString(outStr);
    }

    public static MvcHtmlString MakeBox(HtmlHelper Html, string name)
    {
        return Html.CheckBox(name);
         OR
        return InputExtensions.CheckBox(Html,name);           
    }


回答2:

I assume you are missing a using statement in your extension class.

using System.Web.Mvc.Html;

The CheckBox extension method is within that namespace. HtmlHelper itself is located in System.Web.Mvc which is probably used.



回答3:

Since you don't have the full class, I can't tell if you've included it or not, but make sure you have

using System.Web.Mvc.Html;

in your file.

EDIT: I pasted a different namespace, but I think this is more likely the one you want.