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

gle*_*-84 3 html-helper asp.net-core-mvc asp.net-core

本文介绍如何创建扩展方法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>'
Run Code Online (Sandbox Code Playgroud)

这是如何在MVC6中完成的?

gle*_*-84 11

扩展方法需要打开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());
}
Run Code Online (Sandbox Code Playgroud)

用法:

@(Html.CustomSelectList<Tag>("myId", Model, t => t.Name, t => t.Id.ToString()))
Run Code Online (Sandbox Code Playgroud)

  • 这些信息来自哪里?我一直看到使用`HtmlHelper`,我似乎找不到有关`IHtmlHelper`的任何信息。当然,我无法建立任何参考。 (2认同)