繁体   English   中英

如何使用IDictionary扩展HtmlHelper <string, object> 超载?

[英]How to extend the HtmlHelper with the IDictionary<string, object> overload?

我为HtmlHelper创建了一个扩展方法,该方法很好用。 现在,我需要创建一个接收IDictionary的重载,以便可以向其中添加一个CSS类,因此我尝试了以下操作:

public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
    return EnumDropDownListFor(htmlHelper, expression, null);
}

public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, IDictionary<string, object> htmlAttributes)
{
    var items = DoSomething();

    return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}

当我尝试在我的视图中使用它时,我仍然遇到以下异常:

编译错误

说明:编译服务于此请求所需的资源期间发生错误。 请查看以下特定的错误详细信息,并适当地修改您的源代码。

编译器错误消息:CS1928:'System.Web.Mvc.HtmlHelper'不包含'EnumDropDownListFor'的定义,并且最佳扩展方法重载'LIMM.Web.HtmlHelpers.HtmlDropDownExtensions.EnumDropDownListFor(System.Web.Mvc.HtmlHelper,System .Linq.Expressions.Expression>,System.Collections.Generic.IDictionary)'具有一些无效的参数

显然,我没有正确扩展该方法,但是google并不是我的朋友,无法找到一种方法来实现此目的。 一点帮助将不胜感激。

谢谢。

更新 :在视图中键入代码时,intellisense确实给了我两个重载。 运行应用程序时发生错误。

也许您正在尝试使用最常用的构造(使用html属性作为匿名对象)来使用您的辅助程序,因此很有可能需要这样的重载:

public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
    return EnumDropDownListFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}

public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, IDictionary<string, object> htmlAttributes)
{
    var items = DoSomething();

    return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM