2

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

Community
  • 1
  • 1
Millar
  • 1,095
  • 6
  • 16
  • 34

1 Answers1

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

}
pjumble
  • 16,880
  • 6
  • 43
  • 51