How to create extension method on IHtmlHelper <dynamic>

This article shows how to create an extension method in HtmlHelper<dynamic>

, but it doesn't work with MVC6 (I changed the HtmlHelper to IHtmlHelper).

Mistake:

'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?

+3


source to share


1 answer


The extension method must be on IHtmlHelper

, 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());
}

      



Using:

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

      

+7


source







All Articles