2

我正在尝试使用这个在我的页面上创建一个自定义 html 按钮

public static class HtmlButtonExtension 
{
  public static MvcHtmlString Button(this HtmlHelper helper, string text,
                                     IDictionary<string, object> htmlAttributes)
  {
      var builder = new TagBuilder("button");
      builder.InnerHtml = text;
      builder.MergeAttributes(htmlAttributes);
      return MvcHtmlString.Create(builder.ToString());
  }
}

当我单击此按钮时,我想将 recordID 传递给我的操作

下面给出的是我添加到剃刀视图中的内容

@Html.Button("删除", new {name="CustomButton", recordID ="1" })

但我无法显示这个按钮,而且它正在抛出错误

'System.Web.Mvc.HtmlHelper<wmyWebRole.ViewModels.MyViewModel>' does not contain a definition for 'Button' and the best extension method overload 'JSONServiceRole.Utilities.HtmlButtonExtension.Button(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IDictionary<string,object>)' has some invalid arguments

有人可以帮我找出实际的错误吗

4

1 回答 1

3

You're passing an anonymous object, not an IDictionary<string, object> for htmlAttributes.

You can add an additional overload with object htmlAttributes. This is how they do it in the built-in ASP.NET MVC Html Helpers:

public static class HtmlButtonExtension 
{    
  public static MvcHtmlString Button(this HtmlHelper helper, string text,
                                     object htmlAttributes)
  {
      return Button(helper, text, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
  }

  public static MvcHtmlString Button(this HtmlHelper helper, string text,
                                     IDictionary<string, object> htmlAttributes)
  {
      var builder = new TagBuilder("button");
      builder.InnerHtml = text;
      builder.MergeAttributes(htmlAttributes);
      return MvcHtmlString.Create(builder.ToString());
  }

}
于 2012-05-04T22:38:19.620 回答