Skip to content
July 25, 2011 / pauldundon

LinkButtons in MVC / Razor

The problem: You want the effect of a Web Forms LinkButton in ASP.NET MVC. For example, you may wish to allow the user to take multiple actions on a single form, or have a form submission triggered by a link rather than a button.

Possible Approach: It is possible to use Javascript to change the action attribute on a form, and to use an anchor tag to cause a form submission. So, an anchor tag could modify the action on its parent form to a given controller action and submit the form, thus providing LinkButton-like behaviour.

Possible Solution: Create an extension method for the Html object:

Imports System.Runtime.CompilerServices

Public Module ExtendHTML
    <Extension()>
    Public Function LinkButton(html As HtmlHelper, linkText As String, actionName As String) As MvcHtmlString
        Return html.ActionLink(linkText, actionName, Nothing, New With {.class = "linkButton"})
    End Function
End Module

Include the following Javascript in your page

$(function () {
    $(".linkButton").click(
    function (event) {
        event.preventDefault();
        var link = event.target;
        var action = link.href;
        while (link.tagName != 'FORM') {
            link = link.parentElement;
            if (!link) {
                return;
            }
        }
        link.action = action;
        link.method="POST"
        link.submit();
    });
});

In your .vbhtml file, import your project namespace:

@Imports MyProject

Then use the LinkButton function as follows:

@Html.LinkButton("Click here", "MyAction")

Further Improvements: It would be possible to provide multiple overloads for the LinkButton method to provide support for a wider range of options, generally echoing the overloads of ActionLink.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 215 other followers

%d bloggers like this: