MVC HTML Helper – SubmitLink

Often when creating web applications, it's common for us to want to submit or post forms to the server by using a hyperlink rather than an HTML submit button.  It might be visually more appealing/consistent or whatever your reason might be to have your buttons look like this:

The Cancel button is easy because we can just use a normal Hmtl.ActionLink helper to redirect to whatever our cancel page is.  But what to do for the Save link given that we don't have anything in MVC out of the box that is analogous to the LinkButton in ASP.NET web forms?  One solution might be to just use JavaScript like this:

<a href="javascript:document.mainForm.submit();">Save</a>
<%=Html.ActionLink("Cancel", "Index") %>

But that is somewhat ugly and the paradigm is inconsistent with the Cancel button where we're using a normal ActionLink.  An alternative for this scenario is to just create a simple SubmitLink HTML helper that will allow you're code to look like this:

<%=Html.SubmitLink("Save", "mainForm") %>
<%=Html.ActionLink("Cancel", "Index") %>

You can see this allows us to have a consistent coding paradigm.  The first argument is the link text and the second is the form name.  The implementation looks like this:

public static string SubmitLink(this HtmlHelper htmlHelper, string linkText, string formName, object htmlAttributes)
    TagBuilder tagBuilder = new TagBuilder("a");
    tagBuilder.MergeAttribute("href", string.Format("javascript:document.{0}.submit();", formName));
    tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
    tagBuilder.InnerHtml = linkText;
    return tagBuilder.ToString();
public static string SubmitLink(this HtmlHelper htmlHelper, string linkText, string formName)
    return htmlHelper.SubmitLink(linkText, formName, null);

Notice there is an overload to takes htmlAttributes so that you can apply any arbitrary attributes you might want.  For example, you might want to apply a CSS class that looks like this:

<%=Html.SubmitLink("Save", "mainForm", new { @class = "foo" }) %>

These types of little HTML helpers are so easy to build with MVC, especially given that we can use the TagBuilder class, that it really enables a lot of re-use across your applications.

Tweet Post Share Update Email RSS