Search code examples
html-helperasp.net-coreasp.net-core-mvc

How to create an extension method on IHtmlHelper<dynamic>


This article shows how to create an extension method on HtmlHelper<dynamic>, but it doesn't appear to work with MVC6 (I changed HtmlHelper to IHtmlHelper).

The error is:

'IHtmlHelper<PagedList<Tag>>' does not contain a definition for 'CustomSelectList' and the best extension method overload 'HtmlHelperExtensions.CustomSelectList<Tag>(IHtmlHelper<dynamic>, string, IEnumerable<Tag>, Func<Tag, string>, Func<Tag, string>)' requires a receiver of type 'IHtmlHelper<dynamic>'

How is this done in MVC6?


Solution

  • The extension method needs to be on IHtmlHelper and not on HtmlHelper<dynamic>.

    public static HtmlString CustomSelectList<T>(
        this IHtmlHelper html,
        string selectId,
        IEnumerable<T> list,
        Func<T, string> getName,
        Func<T, string> getValue)
    {
        StringBuilder builder = new StringBuilder();
        builder.AppendFormat("<select id=\"{0}\">", selectId);
        foreach (T item in list)
        {
            builder.AppendFormat("<option value=\"{0}\">{1}</option>",
                getValue(item),
                getName(item));
        }
        builder.Append("</select>");
        return new HtmlString(builder.ToString());
    }
    

    Usage:

    @(Html.CustomSelectList<Tag>("myId", Model, t => t.Name, t => t.Id.ToString()))