如何在IHtmlHelper <dynamic>上创建扩展方法

时间:2015-05-19 13:56:31

标签: html-helper asp.net-core asp.net-core-mvc

This article显示了如何在HtmlHelper<dynamic>上创建扩展方法,但它似乎不适用于MVC6(我将HtmlHelper更改为IHtmlHelper)。

错误是:

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

这是如何在MVC6中完成的?

1 个答案:

答案 0 :(得分:10)

扩展方法需要位于IHtmlHelper而不是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());
}

用法:

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