【问题标题】:MVC3 razor Error in creating HtmlButtonExtensionMVC3 razor 创建 HtmlButtonExtension 时出错
【发布时间】:2012-05-14 11:28:03
【问题描述】:

我正在尝试使用 this 在我的页面上创建一个自定义 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());
  }
}

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

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

@Html.Button("Delete", 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

谁能帮我找出实际的错误

【问题讨论】:

    标签: asp.net-mvc-3 razor


    【解决方案1】:

    您传递的是匿名对象,而不是 IDictionary&lt;string, object&gt;htmlAttributes

    您可以使用object htmlAttributes 添加额外的重载。这就是他们在内置 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());
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多