如何使用IDictionary <string,object =“”>重载扩展HtmlHelper?</string,>

时间:2011-12-19 16:53:26

标签: c# asp.net-mvc-3

我为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&gt;中   System.Collections.Generic.IDictionary)'有一些   无效的参数

显然我没有正确扩展这个方法,但谷歌并没有成为我的朋友找到实现这个目标的方法。我们将不胜感激。

感谢。

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

1 个答案:

答案 0 :(得分:0)

也许你正在尝试使用最常见的构造使用你的助手(将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);
}