asp.net-mvc-3 - MVC3 razor 创建 HtmlButtonExtension 时出错

标签 asp.net-mvc-3 razor

我正在尝试使用 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());
  }
}

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

下面是我添加到 Razor View 中的内容

@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

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

最佳答案

您正在传递一个匿名对象,而不是 IDictionary<string, object>对于 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());
  }

}

关于asp.net-mvc-3 - MVC3 razor 创建 HtmlButtonExtension 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10456956/

相关文章:

asp.net-mvc - 如何将 HTML5 表单操作链接到 ASP.NET MVC 4 中的 Controller ActionResult 方法

ajax - 如何在 View 中显示 actionResult?

html - 布局/HTML 中的 MVC 4 错误

asp.net-mvc-3 - Area 文件夹中的样式、脚本和图像

asp.net-mvc - MVC DataAnnotation 不接受空格

asp.net-mvc-3 - 我需要在 DisplayFor/EditorFor 中使用模型进行数据访问吗?

asp.net - 添加 IIS 模块后 ASP Classic Request.Form 为空

asp.net-mvc - 如何在 ASP.NET MVC View 中对 HTML 列表项进行分组?

c# - 内联 block 似乎不起作用

asp.net-mvc - 使用 Entity Framework 6 和 ViewModel 从数据库表中填充 ASP.NET MVC 中的 DropDownList