MVC3 razor Error in creating HtmlButtonExtension

梦想与她 提交于 2019-12-24 02:55:06

问题


I am trying to create a custom html button on my page using this

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());
  }
}

When I click this button I want to pass an recordID to my Action

Given below is what I added to my razor view

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

But I could not get to display this button,and it's throwing erros

'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

Can some one help me to identify the actual error


回答1:


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());
  }

}


来源:https://stackoverflow.com/questions/10456956/mvc3-razor-error-in-creating-htmlbuttonextension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!