C# - MVC: Create Link-Button

By , 7/6/2015
(0 ratings)
This extension methods create HTML buttons as <Input>-elements which navigates with JavaScript to the given URL respectively Action/Controller.

The usage is like the well known @Html extension methods.

Required Namespaces
System.Text
System.Web.Mvc
/// <summary>
/// Returns an input-element as a button with the given content. It navigates with JavaScript to the given action.
/// </summary>
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));
}
/// <summary>
/// Returns an input-element as a button with the given content. It navigates with JavaScript to the given action in the given controller.
/// </summary>
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));
}

/// <summary>
/// Returns an input-element as a button with the given content. It navigates with JavaScript to the given URL.
/// </summary>
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());
}
Tagged with MVC, Button, Linq, Extension.

Comments

 

Log in, to comment!