An ASP.NET MVC ActionButton HtmlHelper Extension Method

Here's a quick ActionButton HtmlHelper extension method I wrote. Hopefully this will come in handy to someone.

For more information on extension methods, check out Microsoft's MSDN document here, or check out one of my earlier posts here.
public static MvcHtmlString ActionButton(
    this HtmlHelper htmlHelper, string value, object htmlAttributes, string actionName, 
    string controllerName, object routeValues) {     if (String.IsNullOrWhiteSpace(actionName))         throw new ArgumentException("actionName is required.");     if (String.IsNullOrWhiteSpace(controllerName))         throw new ArgumentException("controllerName is required.");     var button = new TagBuilder("input");     button.MergeAttribute("type""button");     button.MergeAttribute("value", value);     button.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));     if (!String.IsNullOrWhiteSpace(actionName))     {         var urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;         button.MergeAttribute("onclick""location.href='" + urlHelper.Action(
            actionName, controllerName, routeValues) + "'");     }     return new MvcHtmlString(button.ToString(TagRenderMode.SelfClosing)); } 


Popular posts from this blog

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception