【问题标题】:How to extend the HtmlHelper with the IDictionary<string, object> overload?如何使用 IDictionary<string, object> 重载扩展 HtmlHelper?
【发布时间】:2011-12-19 16:53:26
【问题描述】:

我为 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)' 有一些 无效参数

很明显,我没有正确扩展该方法,但谷歌在寻找实现这一目标的方法方面并不是我的朋友。我们将不胜感激。

谢谢。

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

【问题讨论】:

  • 您是否确保在视图中添加 using 语句,以便它知道如何找到您的扩展方法?
  • 你见过这个问题吗? stackoverflow.com/questions/7371652/…希望对您有所帮助。
  • @M.Babcock:我当然做到了 :) 就像我说的原始方法工作正常,只是过载有问题。

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


【解决方案1】:

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

【讨论】:

  • 非常感谢,这有效。如果您可以简短解释一下为什么它必须是这样,我相信我们很多人都会从中受益。
  • 我们用来传递一个带有 html 属性的对象。现在还没有从 object 到 Dictionary 的隐式转换,因此,我们需要使用这个签名创建一个重载(html 属性作为 object),并调用将这个对象转换为 Dictionary 的原始方法。 HTMLHelper.AnonymousObjectToHtmlAttributes 方法是专门为完成这种转换而编写的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 2022-06-22
  • 2011-01-29
  • 2012-03-07
相关资源
最近更新 更多