ASP.NET MVC Link-Button

Programming C# ASP.NET MVC

This HTML Helper extension method renders Link-Buttons for a given URL or Action/Controller in a View.

Call in markup:

  • @Html.ActionButton()
  • @Html.LinkButton()

 

using System.Text;
using System.Web.Mvc;

public static MvcHtmlString ActionButton(this HtmlHelper helper, string content, string actionName)
{
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
return LinkButton(helper, content, urlHelper.Action(actionName));
}

public static MvcHtmlString ActionButton(this HtmlHelper helper, string content, string actionName, string controllerName)
{
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
return LinkButton(helper, content, urlHelper.Action(actionName, controllerName));
}

public static MvcHtmlString LinkButton(this HtmlHelper helper, string content, string url)
{
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

var sb = new StringBuilder();
sb.Append("<input type=\"button\" onclick=\"window.location.href='");
sb.Append(urlHelper.Content(url));
sb.Append("';\" value=\"");
sb.Append(content);
sb.Append("\"/>");

return new MvcHtmlString(sb.ToString());
}